How do I create this function which returns true if a number is 5 to an anonymous function:
def yeah_five(p: Int): Boolean = p == 5
thanks?
Short notation for anonymous functions:
(p: Int) => (p == 5);
Long version:
new Function1[Int] {
def apply(p: Int): Int = p == 5
}
You want a function that takes an Integer and returns a Boolean
(p: Int) => (p == 5);
Read through the tutorial on anonymous functions.
I guess the shortest way to write it would be like so:
val f: Int => Boolean = (_ == 5)
Of course, depending on the context you can loose the type annotation:
List(1, 2, 3, 5, 4, 5).filter(_ == 5)
=> List(5, 5)
As per #Senia's observation you can be even more succint with 5== wich transforms the == method of the object 5 to a function.
val g: Int => Boolean = 5==
List(1, 2, 3, 5, 4, 5).filter(g) => List(5, 5)
In case you are want to turn that already declared method into a function, do this
yeah_five _
Related
I create from a json source a csv that I want to use to populate a memsql database with the help of LOAD DATA INFILE.
I have written a typescript script for the conversation and use the library json2csv.
It leaves the values for nulled entries empty though, creating a string like:
foo, bar, , barz, 11 ,
Yet I expect my output to be:
foo, bar, \N , barz, 11 , \N
for my nulled fields. Otherwise, my database will fill in different default values, such as 0 for a number that should be NULL.
I discovered myself doing:
const someEntitites.map((entity: Entity) => {
entity.foo = entity.foo === null ? '\\N' : entity.foo;
entity.bar = entity.bar === null ? '\\N' : entity.bar;
...
return entity;
}
So basically I am hardcoding my approach to my entity, and I also am prone to bug, as I might have forgotten to check a nullable property. And if I am to export another table, I have to repeat this all over again.
How can I generalize this, so I can use this on different entities where the script "discovers" the nullable fields and sets the marker accordingly?
I created a function that iterates over its own properties and sets its value to \N if the according value is null:
const handleNullCases = (record: any): any => {
for (let key in record) {
if (record.hasOwnProperty(key)) {
const value = record[key];
if (value === null) {
record[key] = "\\N";
}
}
}
return record;
};
That way I can reuse that snipplet for other entities as well:
const processedEntities = entities.map(handleNullCases);
const processedEntities2 = entities2.map(handleNullCases);
...
I find it a bit dirty, as that I just typehint for any and cast the value to a string even though it might have been declared as another type.
I'm going to assume all properties in Entity may be null. If so, this typing is a bit safer:
type Nullable<T> = {[K in keyof T]: T[K] | null};
type CSVSafe<T> = {[K in keyof T]: T[K] | '\\N'};
const handleNullCases = <E>(record: Nullable<E>): CSVSafe<E> => {
let ret = Object.assign(record) as CSVSafe<E>;
Object.keys(ret).forEach((key: keyof E) => {
if (record[key] === null) {
ret[key] = '\\N';
}
});
return ret;
};
type Entity = Nullable<{ a: number, b: string, c: boolean, d: number, e: string }>;
const entity: Entity = { a: 1, b: null, c: false, d: null, e: 'e' };
const safeEntity = handleNullCases(entity);
// type CSVSafe<{ a: number; b: string; c: boolean; d: number; e: string; }>
The handleNullCases function will take any object whose values might be null, and return a new object which is just the same except that null values have been replaced with "\\N". The output type will be a CSVSafe<> version of the Nullable<> input type.
Hope that helps.
I'm reading the TypeScript Handbook and in the Functions section under the Function Types heading there is this example (which I understand):
let myAdd = function(x: number, y: number): number { return x+y; };
This is followed by
let’s write the full type of the function out by looking at the each
piece of the function type.
and this syntax:
let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x+y; };
Could someone break this down and explain it as I have never seen this before and can't find an explanation in the handbook?
This line:
let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x+y; };
Consists of 3 parts:
(1) The variable declaration, this part is the let myAdd. I assume that there's nothing to add here, it's just like with js.
(2) The type of the variable: (x: number, y: number) => number.
Here we're defining a type of a function that expects two parameters, both of type number, named x and y.
The function needs to return a number.
(3) The assignment of the value to the variable: = function(x: number, y: number): number { return x+y; }.
This is just like javascript as well, except for the added types for the params and return value.
If you look at it you'll see that the actual implementation matches the declared type perfectly.
You can also write it like this:
let myAdd: (x: number, y: number) => number = function(x, y) { return x+y; };
Or:
let myAdd: (x: number, y: number) => number = (x, y) => { return x+y; };
The first line:
let myAdd: (x: number, y: number) => number
Is declaring the type of the variable "myAdd". Typescript can automatically infer this in the first example, alternatively (which the second example shows) you can implicitly tell Typescript what it should expect.
The second line:
function(x: number, y: number): number { return x+y; };
Refers to the type of the function itself which you have assigned to the variable "myAdd".
For a simpler example illustrating the same thing:
let myString: (input: string) => string = (input: string) => input;
Alternatively a different example of implicitly declaring the variables type:
let myNumber: number = 10;
Both of the above tell Typescript what the variable should be.
As you may know, functions in JavaScript can have properties as any object. For example (taken from the excellent JavaScript: The Definitive Guide, 6th ed, p. 178) computes a factorial using the function as memoization array:
function factorial(n: number): number {
if (isFinite(n) && n > 0 && n == Math.round(n)) {
if (!(n in factorial))
factorial[n] = n * factorial(n - 1);
return factorial[n];
}
else
return NaN;
}
factorial[1] = 1;
I tried defining the following interface:
interface Factorial {
(n: number) : number;
[ index: number ]: number;
}
But the compiler is telling me that Type '(n: number) => number' is not assignable to type 'Factorial'. Index signature is missing in type '(n: number) => number'.
I can't do the obvious thing and just define private index: number; inside the function, I'm stumped.
What you have is an example of hybrid types. You have to use type assertion to make sure the function complies with the interface:
let factorial = function (n: number): number {
if (isFinite(n) && n > 0 && n == Math.round(n)) {
if (!(n in factorial))
factorial[n] = n * factorial(n - 1);
return factorial[n];
}
else
return NaN;
} as Factorial;
factorial[1] = 1;
Can you please help me with this:
I have 2 functions:
f1: Int => Boolean
f2: Int => Boolean
now I want to combine/merge these functions with logical OR, something like:
f3: Int => f1 || f2
so function f3 will return true only if one of functions f1 and f2 returns true
how to write such function?
thanks a lot
def f3(n:Int) = f1(n) || f2(n)
So this is a good bit of infrastructure, but I've found it useful in the past to actually add boolean operations as effectively native operations on predicates. It's one of the things I keep in my grab-bag of utility functionality, and eventually import into pretty much every project I write.
object PredicateUtils {
implicit class RichPredicate[A](f: Function1[A, Boolean]) extends Function1[A, Boolean] {
def apply(v: A) = f(v)
def &&(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) && g(x)
}
def ||(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) || g(x)
}
def unary_! : Function1[A, Boolean] = {
(x: A) => !f(x)
}
}
}
Once you've done that, then all you have to do is
import PredicateUtils
val f3 = f1 || f2
val f4 = !f1 && f2
That would be:
def union(f: Int => Boolean, g: Int => Boolean): Int => Boolean= { x => f(x) || g(x)}
The question here is from where comes 'x', isn't it? Well... it would be the same question as if you ask where f or g come from. You don't even think about that, those are parameters and that suffices. Same answer applies. Forget about the rest of the function. Does x => f(x) || g(x) make sense? As long as f and g return boolean it does, doesn't it? So there you are.
I would say that if you read the whole function from inside out, it has obvious meaning.
Cheers!
def fun_or[T](f1: T => Boolean, f2: T => Boolean)(x: T) = f1(x) || f2(x)
then:
val f3 = fun_or(f1, f2)
examples of composing predicates: http://danielwestheide.com/blog/2013/01/23/the-neophytes-guide-to-scala-part-10-staying-dry-with-higher-order-functions.html
The spray-json library extends basic Scala types with a toJson method. I'd like to convert an Any into a JsValue if there is such a pimp for the underlying type. My best attempt works, but is verbose:
import cc.spray._
val maybeJson1: PartialFunction[Any, JsValue] = {
case x: BigDecimal => x.toJson
case x: BigInt => x.toJson
case x: Boolean => x.toJson
case x: Byte => x.toJson
case x: Char => x.toJson
case x: Double => x.toJson
case x: Float => x.toJson
case x: Int => x.toJson
case x: Long => x.toJson
case x: Short => x.toJson
case x: String => x.toJson
case x: Symbol => x.toJson
case x: Unit => x.toJson
}
Ideally, I'd prefer something (impossible) like this:
def maybeJson2(any: Any): Option[JsValue] = {
if (pimpExistsFor(any))
Some(any.toJson)
else
None
}
Is there a way to do this without enumerating every type that has been enriched?
There is a way, but it requires a lot of reflection and therefore is quite a headache. The basic idea is as follows. The DefaultJsonProtocol object inherits a bunch of traits that contain implicit objects which contain write methods. Each of those will have an accessor function, but you won't know what it's called. Basically, you'll just take all methods that take no parameters and return one object that has a write method that takes the class of your object and returns a JsValue. If you find exactly one such method that returns one such class, use reflection to call it. Otherwise, bail.
It would look something like this (warning, untested):
def canWriteMe(writer: java.lang.Class[_], me: java.lang.Class[_]):
Option[java.lang.reflect.Method] =
{
writer.getMethods.find(_.getName == "write").filter{ m =>
classOf[JsValue].isAssignableFrom(m.getReturnType) && {
val parm = m.getParameterTypes()
m.length == 1 && parm(0).isAssignableFrom(me)
}
}
}
def maybeJson2(any: Any): Option[JsValue] = {
val couldWork = {
DefaultJsonProtocol.getClass.getMethods.
filter(_.getParameterTypes.length==0).
flatMap(m => canWriteMe(m.getReturnType, any.getClass).map(_ -> m))
}
if (couldWork.length != 1) None else {
couldWork.headOption.map{ case (wrMeth, obMeth) =>
val wrObj = obMeth.invoke(DefaultJsonProtocol)
val answer = wrMeth.invoke(wrObj, any)
}
}
}
Anyway, you're best off pulling the DefaultJsonProtocol class apart in the REPL step by step and finding out how to reliably identify the objects that define the writers, and then get the write methods out of them.
I'm not sure it will fit you needs, but here is an alternative approach wich is really simple and type-safe.
If you kept the type of the argument (instead of using Any) you could rely on implicit parameter resolution to find the correct conversion at compile time:
def toJson[T:JsonFormat]( t: T ): JsValue = implicitly[JsonFormat[T]].write(t)
You won't need an option, because the program will fail at compile time if you try to pass an argument which is not "pimpable".