scala referencing value of a parameter - function

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

Related

language ML function val a’ * a’ * int -> bool

In ML language
Suppose f(x,y,z) is a function. Give an example of a definition of f that would cause the argument of f to have the type: a’ * a’ * int.
sample code
fun f1 (x,y,z) = z<5 ;
val f1 = fn : 'a * 'b * int -> bool
how I change this val to a’ * a’ * int -> bool ??
The type:
a’ * a’ * int -> bool
means that the function takes three arguments the first is of 'a type, the second also of 'a type and third of type int.
Your definition:
fun f1 (x,y,z) = z<5 ;
is in the right way since it takes a tuple, now in order to restrict the type of x,y to be equal you could write:
fun f1 (x :'a ,y :'a ,z) = z<5 ;
If you want to avoid explicit type annotations, the simplest way to make x and y the same type is to return both of them from the function but under different circumstances.
Real-world example:
- fun f (x,y,z) = if z < 0 then x else y;
val f = fn : 'a * 'a * int -> 'a
(Since the bool result type isn't mentioned in the problem description, I'm assuming it's just a consequence of your returning z < 5 and not part of the original problem.)

Functions in scala

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.

How to execute code when no result selected using Anorm?

This code works fine when there are records matching the WHERE clause:
val pinfo = SQL("SELECT * FROM tableName WHERE id={id}").on("id" -> "scala")
pinfo().map { row =>
println("have something")// runs when selected
}
What is going to happen when nothing is selected?
I'd like to print the following when no records are selected from MySQL.
println("nothing is selected")//if no row comes
SQL(...)() returns a Stream[SqlRow] and streams have the isEmpty method:
val pinfo: Stream[SqlRow] = SQL("SELECT * FROM tableName WHERE id={id}").on("id" -> "scala")()
if(!pinfo.isEmpty) pinfo.map { row => println("have something") }
else println("nothing is selected")
Also from the REPL:
scala> 1 #:: 2 #:: empty
res0: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> res0.isEmpty
res1: Boolean = false
scala> empty
res2: scala.collection.immutable.Stream[Nothing] = Stream()
scala> res2.isEmpty
res3: Boolean = true
You can also parse it as a Option[T], and then handle the case there is no value within this optional result.
val i: Option[Int] = SQL"SELECT int FROM test".as(scalar[String].singleOpt)

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