Different brackets style on Scala function definition parameter list - function

What is the difference of the following two function definitions in Scala:
1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }
2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }
?
SBT's console REPL gives different value for them so looks if they are somehow different:
sum: (f: Int => Int, a: Int, b: Int)Int
sum: (f: Int => Int)(a: Int, b: Int)Int

The first definition is curried, so that you can provide a and b at another time.
For instance, if you know the function you want to use in the current method, but don't yet know the arguments, you can use it so:
def mySum(v: Int): Int = v + 1
val newsum = sum(mySum) _
At this point, newsum is a function that takes two Ints and returns an Int.
In the context of summing it doesn't seem to make much sense; however, there have been plenty of times I've wanted to return different algorithms for parts of a program based upon something I know now, but don't know (or have access to) the parameters yet.
Currying buys you that feature.

Scala functions support multiple parameter lists to aid in currying. From your first example, you can view the first sum function as one that takes two integers and returns another function (i.e. curries) which can then take an Int => Int function as an argument.
This syntax is also used to create functions that look and behave as new syntax. For example, def withResource(r: Resource)(block: => Unit) can be called:
withResource(res) {
..
..
}

Related

how to pass a Scala function to another function as a function?

I'm just not understanding how to build a function from previous functions.
For example, math.min() function that takes the minimum of two numbers. What if I wanted to create a function min3Z(a:int, b:int, c:Int)? How would I build this from min?
Your question is unclear. Are you simply trying to utilize math.min() in min3Z()? Because in that case, you can do:
def min3Z(a: Int, b: Int, c: Int) = math.min(a, math.min(b, c))
If you want to pass in an arbitrary function (for example, making it so you can specify max or min), you can specify a function as a parameter:
def min3Z(a: Int, b: Int, c: Int, f: (Int, Int) => Int) = f(a, f(b, c))
The syntax (Int, Int) => Int in Scala is the type for a function that takes two parameters of type Int and returns a result of type Int. math.min() and math.max() both fit this criteria.
This allows you to call min3Z as min3Z(1, 2, 3, math.min) or min3Z(1, 2, 3, math.max). It's even possible to make a version of min3Z() that takes an arbitrary number of Ints and an arbitrary (Int, Int) => Int function, but that's beyond the scope of your question.
If implementing min for three values is your specific case you may want to generalize to an arbitrary number of arguments by using a variadic (aka varargs) function as follows:
def min(xs: Int*): Int = xs.min
The variadic syntax is denoted by the * symbol after the type declaration--Int in this case. This way all the following calls would work:
min(1, 2)
min(1, 2, 3, 4, 5, 6, -1)
// and so on...
Talking about being generic you could also write an even more generic min that accepts any numeric type, not only Int ones:
def min[T : Numeric](xs: T*): T = xs.reduceLeft(implicitly[Numeric[T]].min)
An use it as follows:
min(1, 2, 3, 4)
min(1.2, 3.4, 5.6, 4.2)

passing 2 arguments to a function in Haskell

In Haskell, I know that if I define a function like this add x y = x + y
then I call like this add e1 e2. that call is equivalent to (add e1) e2
which means that applying add to one argument e1 yields a new function which is then applied to the second argument e2.
That's what I don't understand in Haskell. in other languages (like Dart), to do the task above, I would do this
add(x) {
return (y) => x + y;
}
I have to explicitly return a function. So does the part "yields a new function which is then applied to the second argument" automatically do underlying in Haskell? If so, what does that "hiding" function look like? Or I just missunderstand Haskell?
In Haskell, everything is a value,
add x y = x + y
is just a syntactic sugar of:
add = \x -> \y -> x + y
For more information: https://wiki.haskell.org/Currying :
In Haskell, all functions are considered curried: That is, all functions > in Haskell take just single arguments.
This is mostly hidden in notation, and so may not be apparent to a new
Haskeller. Let's take the function
div :: Int -> Int -> Int
which performs integer division. The expression div 11 2
unsurprisingly evaluates to 5. But there's more that's going on than
immediately meets the untrained eye. It's a two-part process. First,
div 11
is evaluated and returns a function of type
Int -> Int
Then that resulting function is applied to the value 2, and yields 5.
You'll notice that the notation for types reflects this: you can read
Int -> Int -> Int
incorrectly as "takes two Ints and returns an Int", but what it's
really saying is "takes an Int and returns something of the type Int
-> Int" -- that is, it returns a function that takes an Int and returns an Int. (One can write the type as Int x Int -> Int if you
really mean the former -- but since all functions in Haskell are
curried, that's not legal Haskell. Alternatively, using tuples, you
can write (Int, Int) -> Int, but keep in mind that the tuple
constructor (,) itself can be curried.)

Create 1 function from 2 other functions in scala?

This question relates to the scala course from coursera so I want to please ask you to not give me the plain solution that I can copy-paste as this would break the coursera honor code.
This relates to the second assignment.
def Set = Int => Boolean
As it can be seen, Set is a function which returns weather or not the given int is or not part of the set. This is plain and simple so far. However the task asks me to create a union
def union(f: Set, s: Set): Set = ???
This union should return a set that satisfies the condition of both sets.
How could I do something like this:
I thought that such a thing could be done by adding the functions together however the following code:
f + s
Will not compile properly as expected
My question to is:
How would I be able to create a function from 2 other functions?
x => if x == 0 true else false //first
x => if x == 1 true else false //second
And what should equal:
x => if x==0 || x == 1 true else false
I'm not asking for a solution but rather how would I go around building something like this?
As I think you already understand, these Sets are functions that test whether a value meets the criteria for each Set.
The union of such a Set must also be a function that returns a Boolean (as shown by the type signature)
def union(f: Set, s: Set): Set
which (because Set is a type alias) is equivalent to:
def union(f: Int => Boolean, s: Int => Boolean): Int => Boolean
In plain English, union of two sets A and B means: "is the item in A or B".
Your task is to write a function that carries out that plain English specification.
You cannot "add" two functions together (at least, not in a way that is applicable to this question), but you can combine their results.
The Set has form of Set = Int => Boolean. Given the Int function will return true if the value is in a Set.
Well if we want to create a singleton set, we will return new function, which will compare any value passed to it, with the one passed to the function that created it.
The union of two sets, is one set plus the other. It means the element you're looking for must be either in one or the other set. But how do we get the new set, well we return a new function that does just that - checks if an element is either in one set or another.
Remember that in Scala functions can return functions, which may be evaluated later. I think that's the key.
The Set is defined as a function from Int to Boolean, "summing" two Sets won't return a Set object, the union means that one element should be either in one or in the other set but always expressed as a function.
I hope this is not too much, but given an element it should satisfy either f or s.
First of all, it's type Set =. Not def. Set is a type alias not a function definition.
Now, your question. You need a function which, when given two Int =>Boolean combines them with OR and returns a Int => Boolean.
First, how would you do this for two Boolean arguments?
def or(a: Boolean, b: Boolean) = a || b
So now we're half way there. What we have:
A pair of Int => Boolean functions.
A function that takes two Booleans and return a Boolean.
So all we need to do is apply each Set to an Int to get a Boolean and OR the result. The confusion is probably here.
The easiest way to curry a function is to do it explicitly
def union(f: Set, s: Set): Set = {
def doUnion(x: Int) = //apply x to f and s, return OR
doUnion
}
But we can, in Scala, so this inline by declaring an anonymous function
def union(f: Set, s: Set): Set = x => //apply x to f and s, return OR

def or val for defining Function in Scala

I'm learning Programming Paradigms in my University and reading this course material provided by the lecturer that defined a function this way:
val double = (x: Int) => 2 * x
double: Int => Int = <function1>
But from my own studies I found and got used to defining the same function like this:
def d (x: Int) = 2 * x
d: (x: Int)Int
I'm new to Scala. And both definitions give a result of:
res21: Int = 8
Upon passing 4 as the parameter.
Now my main question is why would the lecturer prefer to use val to define a function? I see it as longer and not really necessary unless using val gives some added advantages that I don't know of. Besides I understand using val makes some name a placeholder so later in the program, I could mistakenly write val double = 5 and the function would be gone!
At this stage I'm quite convinced I learned a better way of defining a function unless someone would tell me otherwise.
Strictly speaking def d (x: Int) = 2 * x is a method, not a Function, however scala can transparently convert (lift) methods into Functions for us. So that means you can use the d method anywhere that requires a Int => Int Function.
There is a small overhead of performing this conversion, as a new Function instance is created every time. We can see this happening here:
val double = (x: Int) => 2 * x
def d (x: Int) = 2 * x
def printFunc(f: Int => Int) = println(f.hashCode())
printFunc(double)
printFunc(double)
printFunc(d)
printFunc(d)
Which results in output like so:
1477986427
1477986427
574533740
1102091268
You can see when explicitly defining a Function using a val, our program only creates a single Function and reuses it when we pass as an argument to printFunc (we see the same hash code). When we use a def, the conversion to a Function happens every time we pass it to printFunc and we create several instances of the Function with different hash codes. Try it
That said, the performance overhead is small and often doesn't make any real difference to our program, so defs are often used to define Functions as many people find them more concise and easier to read.
In Scala, function values are monomorphic (i.e. they can not have type parameters, aka "generics"). If you want a polymorphic function, you have to work around this, for example by defining it using a method:
def headOption[A]: List[A] => Option[A] = {
case Nil => None
case x::xs => Some(x)
}
It would not be valid syntax to write val headOption[A]. Note that this didn't make a polymorphic function value, it is just a polymorphic method, returning a monomorphic function value of the appropriate type.
Because you might have something like the following:
abstract class BaseClass {
val intToIntFunc: Int => Int
}
class A extends BaseClass {
override val intToIntFunc = (i: Int) => i * 2
}
So its purpose might not be obvious with a very simple example. But that Function value could itself be passed to higher order functions: functions that take functions as parameters. If you look in the Scala collections documentation you will see numerous methods that take functions as parameters. Its a very powerful and versatile tool, but you need to get to a certain complexity and familiarity with algorithms before the cost /benefit becomes obvious.
I would also suggest not using "double" as an identifier name. Although legal Scala, it is easy to confuse it with the type Double.

Is there any difference between this syntax of curried functions?

Another Scala Newbie question.
Trying to find the difference between:
def _1_sumUntil(n: Int) = (f: Int => Int) => (0 to n).toList.foldLeft(0){(a,b) => a + f(b)}
and
def _2_sumUntil(n: Int)(f: Int => Int) = (0 to n).toList.foldLeft(0){(a,b) => a + f(b)}
what is the advantage of one over the other (if at all) ?
The first is a method with one parameter list that returns a function from Int => Int to Int, the second is a method with two parameter lists that returns an Int.
Technically, by means of what is called eta-expansion—a method can be transparently converted to a function value—, the second method can be partially applied, yielding the same function as the first method:
val a = _1_sumUntil(33) // (Int => Int) => Int
val b = _2_sumUntil(33) _ // (Int => Int) => Int via eta-expansion
My advise is to use the second variant and avoid explicit function values. The advantage of the second is that—unless you do use eta-expansion—no function value is instantiated (apart from the function passed to foldLeft) which is then applied. Also it is arguably easier to read.
I would use the first version only if the main purpose of the method is really to give you a function from Int => Int to Int to pass around.
See also this question and this question.