Functions in scala - function

I'm having hard time understanding what the following means in scala:
f: Int => Int
Is the a function?
What is the difference between f: Int => Intand def f(Int => Int)?
Thanks

Assuming f: Int => Int is a typo of val f: Int => Int,
and def f(Int => Int) is a typo of def f(i: Int): Int.
val f: Int => Int means that a value f is Function1[Int, Int].
First, A => B equals to =>[A, B].
This is just a shortcut writing, for example:
trait Foo[A, B]
val foo: Int Foo String // = Foo[Int, String]
Second, =>[A, B] equals to Function1[A, B].
This is called "type alias", defined like:
type ~>[A, B] = Foo[A, B]
val foo: Int ~> String // = Foo[Int, String]
def f(i: Int): Int is a method, not a function.
But a value g is Function1[Int, Int] where val g = f _ is defined.

f: Int => Int
means that type of f is Int => Int.
Now what does that mean? It means that f is a function which gets an Int and returns an Int.
You can define such a function with
def f(i: Int): Int = i * 2
or with
def f: Int => Int = i => i * 2
or even with
def f: Int => Int = _ * 2
_ is a placeholder used for designating the argument. In this case the type of the parameter is already defined in Int => Int so compiler knows what is the type of this _.
The following is again equivalent to above definitions:
def f = (i:Int) => i * 2
In all cases type of f is Int => Int.
=>
So what is this arrow?
If you see this arrow in type position (i.e. where a type is needed) it designates a function.
for example in
val func: String => String
But if you see this arrow in an anonymous function it separates the parameters from body of the function. For example in
i => i * 2

To elaborate just slightly on Nader's answer, f: Int => Int will frequently appear in a parameter list for a high order function, so
def myHighOrderFunction(f : Int => Int) : String = {
// ...
"Hi"
}
is a dumb high order function, but shows how you say that myOrderFunction takes as a parameter, f, which is a function that maps an int to an int.
So I might legally call it like this for example:
myHighOrderFunction(_ * 2)
A much more illustrative example comes from Odersky's Programming Scala:
object FileMatcher {
private def filesHere = (new java.io.File(".")).listFiles
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere if matcher(file.getName))
yield file
def filesEnding(query: String) = filesMatching(_.endsWith(query))
def filesContaining(query: String) = filesMatching(_.contains(query))
def filesRegex(query: String) = filesMatching(_.matches(query))
}
Here filesMatching is a high order function, and we define three other functions that call it passing in different anonymous functions to do different kinds of matching.
Hope that helps.

Related

andThen for function of two arguments in Scala

Suppose I have two functions f and g:
val f: (Int, Int) => Int = _ + _
val g: Int => String = _ + ""
Now I would like to compose them with andThen to get a function h
val h: (Int, Int) => String = f andThen g
Unfortunately it doesn't compile :(
scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
val h = (f andThen g)
Why doesn't it compile and how can I compose f and g to get (Int, Int) => String ?
It doesn't compile because andThen is a method of Function1 (a function of one parameter: see the scaladoc).
Your function f has two parameters, so would be an instance of Function2 (see the scaladoc).
To get it to compile, you need to transform f into a function of one parameter, by tupling:
scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>
test:
scala> val t = (1,1)
scala> h(t)
res1: String = 2
You can also write the call to h more simply because of auto-tupling, without explicitly creating a tuple (although auto-tupling is a little controversial due to its potential for confusion and loss of type-safety):
scala> h(1,1)
res1: String = 2
Function2 does not have an andThen method.
You can manually compose them, though:
val h: (Int, Int) => String = { (x, y) => g(f(x,y)) }

scala referencing value of a parameter

If I have the following type and function:
object M {
type X[Boolean] = Int => Boolean
def retrieveVal(x: X[Boolean]) : Boolean = //retrieve the Boolean value of x
}
How would I go about retrieving and returning the boolean value?
That is a peculiar type alias. It has a formal type parameter (the name of which is irrelevant and hence the choice of Boolean is misleading) that defines a function from Int to that arbitrary type. You then define a method, retrieveVal that takes a particular kind of X that happens to be X[Boolean] (here Boolean is an actual type parameter and hence is the Boolean we're familiar with) and returns some Boolean. However, the function x passed as an argument requires an Int argument and there is none in evidence.
So, if your retrieveVal were defined like this instead:
def retrieveVal(i: Int, x: X[Boolean]): Boolean = ...
you could define it like this:
def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)
To wit:
scala> type X[Boolean] = Int => Boolean
defined type alias X
scala> def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)
retrieveVal: (i: Int, x: Int => Boolean)Boolean
scala> retrieveVal(23, i => i % 2 == 0)
res0: Boolean = false

SML - Creating dictionary that maps keys to values

I need to create a dictionary in sml, but I am having extreme difficulty with an insert function.
type dict = string -> int option
As an example, here is the empty dictionary:
val empty : dict = fn key => NONE
Here is my implementation of an insert function:
fun insert (key,value) d = fn d => fn key => value
But this is of the wrong type, what I need is insert : (string*int) -> dict -> dict.
I've searched everything from lazy functions to implementing dictionaries.
Any help or direction would be greatly appreciateds!
If you are still confused on what I am trying to implement, I drafted up what I should expect to get when calling a simple lookup function
fun lookup k d = d k
- val d = insert ("foo",2) (insert ("bar",3) empty);
val d = fn : string -> int option
- lookup2 "foo" d;
val it = SOME 2 : int option
- lookup2 "bar" d;
val it = SOME 3 : int option
- lookup2 "baz" d;
val it = NONE : int option
You can reason on the signature of the function:
val insert = fn: (string * int) -> dict -> dict
When you supply key, value and a dictionary d, you would like to get back a new dictionary d'. Since dict is string -> int option, d' is a function takes a string and returns an int option.
Suppose you supply a string s to that function. There are two cases which could happen: when s is the same as key you return the associated value, otherwise you return a value by looking up d with key s.
Here is a literal translation:
fun insert (key, value) d = fn s => if s = key then SOME value
else d s

Scala Functional Literals with Implicits

Forgive me if this has already been asked elsewhere. I have a Scala syntax question involving function-values and implicit parameters.
I'm comfortable using implicits with Scala's currying feature. For instance if I had a sum function and wanted to make the second argument an implicit:
scala> def sum(a: Int)(implicit b: Int) = a + b
sum: (a: Int)(implicit b: Int)Int
Is there a way to do this using the function-value syntax? Ignoring the implicit for a moment, I typically write curried function-values like this:
scala> val sum2 = (a: Int) => (b: Int) => a + b
sum: (Int) => (Int) => Int = <function1>
However, the function signature in the second approach is much different (the currying is being expressed explicitly). Just adding the implicit keyword to b doesn't make much sense and the compiler complains as well:
scala> val sum2 = (a: Int) => (implicit b: Int) => a + b
<console>:1: error: '=>' expected but ')' found.
val sum2 = (a: Int) => (implicit b: Int) => a + b
^
Furthermore partially-applying sum from the very first approach to get a function-value causes problems as well:
scala> val sumFunction = sum _
<console>:14: error: could not find implicit value for parameter b: Int
val sumFunction = sum _
^
This leads me to believe that functions that have implicit parameters must have said parameters determined when the function-value is created, not when the function-value is applied later on. Is this really the case? Can you ever use an implicit parameter with a function-value?
Thanks for the help!
scala> val sum2 = (a: Int) => {implicit b: Int => a + b}
sum2: (Int) => (Int) => Int = <function1>
This will just make b an implicit value for the scope of the function body, so you can call methods that expect an implicit Int.
I don't think you can have implicit arguments for functions since then it is unclear what the function is. Is it Int => Int or () => Int?
The closest I found is:
scala> case class Foo(implicit b: Int) extends (Int => Int) {def apply(a: Int) = a + b}
defined class Foo
scala> implicit val b = 3
b: Int = 3
scala> Foo()
res22: Foo = <function1>
scala> res22(2)
res23: Int = 5
In this snippet
scala> val sum2 = (a: Int) => (b: Int) => a + b
sum: (Int) => (Int) => Int = <function1>
Note that the precise type of sum2 is Function1[Int, Function1[Int, Int]]. It could also be written as
val sum2 = new Function1[Int, Function1[Int, Int]] {
def apply(a: Int) = new Function1[Int, Int] {
def apply(b: Int) = a + b
}
}
Now, if you try to make b implicit, you get this:
scala> val sum2 = new Function1[Int, Function1[Int, Int]] {
| def apply(a: Int) = new Function1[Int, Int] {
| def apply(implicit b: Int) = a + b
| }
| }
<console>:8: error: object creation impossible, since method apply in trait Function1 of type (v1: Int)Int is not defined
def apply(a: Int) = new Function1[Int, Int] {
^
Or, in other words, Function's interfaces do not have implicit parameters, so anything with an implicit parameter is not a Function.
Try overloading the apply method.
scala> val sum = new Function1[Int, Function1[Int, Int]] {
| def apply(a: Int) = (b: Int) => a + b
| def apply(a: Int)(implicit b: Int) = a + b
|}
sum: java.lang.Object with (Int) => (Int) => Int{def apply(a:Int)(implicit b: Int): Int} = <function1>
scala> sum(2)(3)
res0: Int = 5
scala> implicit val b = 10
b: Int = 10
scala> sum(2)
res1: Int = 12

How to return a function in scala

How can I return a function side-effecting lexical closure1 in Scala?
For instance, I was looking at this code sample in Go:
...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())
prints
1 2 3 5 8
And I can't figure out how to write the same in Scala.
1. Corrected after Apocalisp comment
Slightly shorter, you don't need the return.
def fib() = {
var a = 0
var b = 1
() => {
val t = a;
a = b
b = t + b
b
}
}
Gah! Mutable variables?!
val fib: Stream[Int] =
1 #:: 1 #:: (fib zip fib.tail map Function.tupled(_+_))
You can return a literal function that gets the nth fib, for example:
val fibAt: Int => Int = fib drop _ head
EDIT: Since you asked for the functional way of "getting a different value each time you call f", here's how you would do that. This uses Scalaz's State monad:
import scalaz._
import Scalaz._
def uncons[A](s: Stream[A]) = (s.tail, s.head)
val f = state(uncons[Int])
The value f is a state transition function. Given a stream, it will return its head, and "mutate" the stream on the side by taking its tail. Note that f is totally oblivious to fib. Here's a REPL session illustrating how this works:
scala> (for { _ <- f; _ <- f; _ <- f; _ <- f; x <- f } yield x)
res29: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#d53513
scala> (for { _ <- f; _ <- f; _ <- f; x <- f } yield x)
res30: scalaz.State[scala.collection.immutable.Stream[Int],Int] = scalaz.States$$anon$1#1ad0ff8
scala> res29 ! fib
res31: Int = 5
scala> res30 ! fib
res32: Int = 3
Clearly, the value you get out depends on the number of times you call f. But this is all purely functional and therefore modular and composable. For example, we can pass any nonempty Stream, not just fib.
So you see, you can have effects without side-effects.
While we're sharing cool implementations of the fibonacci function that are only tangentially related to the question, here's a memoized version:
val fib: Int => BigInt = {
def fibRec(f: Int => BigInt)(n: Int): BigInt = {
if (n == 0) 1
else if (n == 1) 1
else (f(n-1) + f(n-2))
}
Memoize.Y(fibRec)
}
It uses the memoizing fixed-point combinator implemented as an answer to this question: In Scala 2.8, what type to use to store an in-memory mutable data table?
Incidentally, the implementation of the combinator suggests a slightly more explicit technique for implementing your function side-effecting lexical closure:
def fib(): () => Int = {
var a = 0
var b = 1
def f(): Int = {
val t = a;
a = b
b = t + b
b
}
f
}
Got it!! after some trial and error:
def fib() : () => Int = {
var a = 0
var b = 1
return (()=>{
val t = a;
a = b
b = t + b
b
})
}
Testing:
val f = fib()
println(f(),f(),f(),f())
1 2 3 5 8
You don't need a temp var when using a tuple:
def fib() = {
var t = (1,-1)
() => {
t = (t._1 + t._2, t._1)
t._1
}
}
But in real life you should use Apocalisp's solution.