side-effects for `wye` combinators when using `halt` from scalaz-stream - scalaz

filter (which uses halt inside) terminates other branch even if it has some side-effects:
scala> val p = Process("1","2", "3")
scala> val p1 = p.filter(_ => true).map(_ + "p1").observe(io.stdOutLines)
scala> val p2 = p.filter(_ => false).map(_ + "p2").observe(io.stdOutLines)
scala> (p1 yip p2).run.run
1p1
scala> val p2 = p.filter(_ => true).map(_ + "p1").observe(io.stdOutLines)
scala> (p1 yip p2).run.run
1p1
1p2
2p1
2p2
3p1
3p2
Seems logical as there is no value to be returned to yip after that filter. But what about side-effects, specified with observe?
My current solution is to use flatMap to specify default value:
scala> val p1 = p.map(_ + "p1").flatMap(x => Process.emit(x).observe(io.stdOutLines))
scala> val p2 = p.map(_ + "p2").flatMap(x => Process.emit(""))
scala> (p1 yip p2).run.run
1p1
2p1
3p1
But maybe there is a way to use filter?
P.S. merge combinator executes side-effects for other branch (as it doesn't require value to be returned), but it doesn't wait for other branch if one halts (even if it has side-effects).

To run the effects even after p2 terminates there needs to be clear default behaviour. So there are probably these solutions:
define p2 to supply default value after being terminated
use either wye to get left and rights if we don't really need tuples
perhaps the (1) is closer to question and code will looks like:
val p = Process("1","2", "3")
val p1 = p.filter(_ => true).map(_ + "p1").observe(io.stdOutLines)
val p2 = p.filter(_ => false).map(_ + "p2")
.observe(io.stdOutLines).map(Some(_)) ++ emit(None).repeat
// alternativelly
// val p2 = p.map { v => if (pred(v)) right(v) else left(v) }
// .observeO(o.stdOutLines).flatMap { _.toOption }
// ++ emit(None).repeat
(p1 yip p2).run.run

Actually it should be just something like that:
in.map(emit).flatMap{ p =>
val p1 = p.map(_ + "p1").filter(_ => true).observe(out)
val p2 = p.map(_ + "p2").filter(_ => false).observe(out)
p1 merge p2
}.run.run
It makes all side effects being in order as filter can't get more than one value (produced by emit)

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)) }

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)

Difference between these two method definitions

What's the difference between these two definitions?:
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)
What is the purpose of each?
The second is curried, the first isn't. For a discussion of why you might choose to curry a method, see What's the rationale behind curried functions in Scala?
sayTwords2 allows the method to be partially applied.
val sayHelloAnd = sayTwords2("Hello")
sayHelloAnd("World!")
sayHaelloAnd("Universe!")
Note you can also use the first function in the same way.
val sayHelloAnd = sayTwords("Hello", _:String)
sayHelloAnd("World!")
sayHelloAnd("Universe!")
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)
The first contains a single parameter list. The second contains multiple parameter lists.
They differ in following regards:
Partial application syntax. Observe:
scala> val f = sayTwords("hello", _: String)
f: String => Unit = <function1>
scala> f("world")
hello world
scala> val g = sayTwords2("hello") _
g: String => Unit = <function1>
scala> g("world")
hello world
The former has a benefit of being positional syntax. Thus you can partially apply arguments in any positions.
Type inference. The type inference in Scala works per parameter list, and goes from left to right. So given a case, one might facilitate better type inference than other. Observe:
scala> def unfold[A, B](seed: B, f: B => Option[(A, B)]): Seq[A] = {
| val s = Seq.newBuilder[A]
| var x = seed
| breakable {
| while (true) {
| f(x) match {
| case None => break
| case Some((r, x0)) => s += r; x = x0
| }
| }
| }
| s.result
| }
unfold: [A, B](seed: B, f: B => Option[(A, B)])Seq[A]
scala> unfold(11, x => if (x == 0) None else Some((x, x - 1)))
<console>:18: error: missing parameter type
unfold(11, x => if (x == 0) None else Some((x, x - 1)))
^
scala> unfold(11, (x: Int) => if (x == 0) None else Some((x, x - 1)))
res7: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> def unfold[A, B](seed: B)(f: B => Option[(A, B)]): Seq[A] = {
| val s = Seq.newBuilder[A]
| var x = seed
| breakable {
| while (true) {
| f(x) match {
| case None => break
| case Some((r, x0)) => s += r; x = x0
| }
| }
| }
| s.result
| }
unfold: [A, B](seed: B)(f: B => Option[(A, B)])Seq[A]
scala> unfold(11)(x => if (x == 0) None else Some((x, x - 1)))
res8: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

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.