Scala anonymous function (creating a new function based on one passed) - scala

I've a function where I'm trying to modify a function I've been passed (p) in an anonymous function, then use it as a parameter to f2.
Here's the code;
def f1(i: Int, p: Int => Boolean): Boolean = {
!f2(s,(a :Int=>Boolean) = !p(a) )
}
def f2(i: Int, p: Int => Boolean): Boolean
But this won't compile due to missing markers, and I'm a bit stumped.
James

Maybe you want to try and do this:
def f1(i: Int, p: Int => Boolean): Boolean = {
!f2(i,(a :Int=>Boolean) = !p )
}
def f2(i: Int, p: Int => Boolean): Boolean

Gzou was right, the problem I had was not including a space between the => and !. Thanks for that, very helpful,

Related

High order functions in Scala

IM trying to understand the below high order functions in Scala but need some clarifications on the parameters of the functions.
Questions:-
What does the Int => String in the apply function mean?
v: Int indicates that the parameter v is of type Int.
What does the [A](x: A) mean in layout function?
object Demo {
def main(args: Array[String]) {
println( apply( layout, 10) )
}
def apply(f: Int => String, v: Int) = f(v)
def layout[A](x: A) = "[" + x.toString() + "]"
}
f: Int => String means that f is a function with one argument of type Int and with a return type String
def layout[A](x: A) means that parameter x is of type A, which can be of any type. Here are a couple of examples on how to invoke layout:
layout[String]("abc") //returns "[abc]"
layout[Int](123) //returns "[123]"
When main runs it invokes apply with the layout function and the argument 10. This will output "[10]"
The syntax of Int => String means passing a function that accepts Int and returns String.
Here is a useful example for passing function:
case class Person(name: String, lastName: String)
val person = Person("Johnny", "Cage")
def updateName(name: String) = {
updatePerson(_.copy(name = name))
}
def updateLastName(lastName: String) {
updatePerson(_.copy(lastName = lastName))
}
private def updatePerson(transformer: Person => Person): Unit = {
transformer(person)
}
Note how each update function passes the copy constructor.

What is the purpose of outer and inner function parameters in Scala?

In the following code:
def product(f: Int => Int)(a:Int, b:Int): Int =
if (a > b) 1
else f(a) * product(f)(a + 1, b)
The parameters a and b are passed to the inner function, but you could write exactly the same function definition like so:
def product(f: Int => Int, a:Int, b:Int): Int =
if (a > b) 1
else f(a) * product(f, a + 1, b)
So what is the purpose of separating the parameters? In other words, why do this:
(f: Int => Int)(a:Int, b:Int)
when you can more clearly write:
(f: Int => Int, a:Int, b:Int)
Another feature of multiple parameters lists is partial application:
def sum3(a: Int)(b: Int)(c: Int): Int = a + b + c
val g: Int => Int => Int = sum3(10) _
val h: Int => Int = g(20)
val r: Int = h(30) // 10 + 20 + 30 = 60
You can partially apply a function and obtain another function which is equivalent to the original one but with one of the arguments fixed. _ after sum3(10) is needed because sum3 is a method, not a function, and _ converts methods to functions.
This is very useful when you are using higher-order functions:
def adder(x: Int)(y: Int) = x + y
Seq(1, 2, 3, 4) map adder(10) // Seq(11, 12, 13, 14)
When partially applied method/function is used as an argument of a higher-order call, _ is not needed, and the syntax becomes very succinct.
Another use case of this feature is that if you want to create a control structure that looks like it's built into Scala programming language itself.
For example, I could write an control structure named times which help me execute the code block exactly n times by the following method definition:
// since block is call by name, it will not be evaluate when you call it.
def times(n: Int)(block: => Any): Unit = {
for (i <- 0 until n) {
block // evaluate(execute) block
}
}
// Now I can use the times method like a control structure
times(5) {
println("Hello World");
}
It depends whether there is implicit parameter (which can't be properly mixed with plain ones)...
def foo(i: Int)(implicit p: P): Foo
... and the way you want to call it ...
def foo1(a: Int)(b: Int => Boolean): Boolean
foo1(9) { i => false }
def foo2(a: Int, b: Int => Boolean): Boolean
foo2(9, { i => false })

Modify function passed as argument

I have two functions. One is masterChecker, wich takes as argument an Int x and a function p, and return the boolean result p(x). Simple like that.
def masterChecker(x: Int, p: Int => Boolean): Boolean = p(x)
Then I have a second function childChecker, which is like an alias to masterChecker
def childChecker(x: Int, f: Int => Boolean): Boolean = masterChecker(x , f)
Is there any way to change f in the masterCheker call on childChecker, in a manner that it would run like !f ? (if f return true, than make it false)
Like:
// inside childChecker
masterChecker(x, !f)
I know that I could do it on the masterChecker call with !masterChecker(x,f), but what I want to know is if it´s possible to change a function behavior passed as an argument.
Sure, you can use an anonymous function like so:
def childChecker(x: Int, f: Int => Boolean) = masterCheck(x, !f(_))
and there you go!
Even more so, you could do a number of things if you want to "modify" f within the function scope of childChecker:
def childChecker(x: Int, f: Int => Boolean) ={
def proxy(x: Int): Boolean ={
val y: Int = //do things
f(y) //see? "y" not "x"
}
masterCheck(x, proxy)
}
that's part of the fun when you're dealing with plain ol' functions. Granted, this "modification" is more of a decorator pattern but it does adhere to the interface.

reversing the boolean return type from a function

I have two functions which accept a function type: Int => Boolean function type
def myFunction1(f1: Int => Boolean) ...
def myFunction2(f2: Int => Boolean) ...
I want to call function2 from function1 but instead of just invoking it with f1, I want to invoke it with the inverse of f1. So if f1 is something like
(x: Int) => x > 4
at runtime, i.e. return true for numbers greater than four. I want the reverse returns false if numbers are greater than four. Is it possible to inverse f1 before calling myFunction2?
You could do something like this:
def myFunction1(f1: Int => Boolean) = myFunction2(!f1(_))
def myFunction1(f1: Int => Boolean) = myFunction2(f1 andThen (! _))

Where do you split long Scala function signatures?

A definition like
def foo(x: Int) = x + 1
is nice and short and looks pretty, but when the signature itself gets uncomfortably long,
def foo[T <: Token[T]](x: ArrayBuffer[T], y: T => ArrayBuffer[() => T]): (T, T, BigDecimal) = {
// ...
}
I don't know where to split it. I find all of the following to look awkward:
def foo(
x: Int,
y: Int
): Int = {
// ...
}
def foo(
x: Int,
y: Int
): Int =
{
// ...
}
def foo(
x: Int,
y: Int
): Int
= {
// ...
}
def foo(
x: Int,
y: Int
):
Int = {
// ...
}
But, given that I'm going to have to get used to one of these, which will cause the least annoyance to my teammates?
The Scala style guide has nothing to say on this. In fact it recommends using methods with fewer parameters :-).
For function invocations it does recommend splitting so that each subsequent line aligns with the first parenthesis:
foo(someVeryLongFieldName,
andAnotherVeryLongFieldName,
"this is a string",
3.1415)
Personally in your case I would split according to a 'keep like things together' rule:
def foo[T <: Token[T]]
(x: ArrayBuffer[T], y: T => ArrayBuffer[() => T])
: (T, T, BigDecimal) = {
// ...
}
So the parameters are on one line, the return type is on a single line and the type restriction is on a single line.
In Haskell, long type signatures are often written in this fashion:
someFunc :: (Some Constraints Go Here)
=> Really Long Arg1 Type
-> Really Long Arg2 Type
-> Really Long Result Type
somefunc x y = ...
To translate this Haskellism into Scala,
def foo [ T <: Token[T] ]
( x : ArrayBuffer[T]
, y : T => ArrayBuffer[() => T]
) : (T, T, BigDecimal) = {
// ...
}
That's how I would do it. Not sure how kosher it is with the Scala community.