Learning Scala 3 with monadic topics.
came across understandable breakdown of Continuation monad at https://jsdw.me/posts/haskell-cont-monad/
When I try to adopt simple code into Scala
twoC = \out -> out 2
helloC = \out -> out "hello"
ret val = \out -> out val
inC `bind` fn = \out -> inC (\inCval -> (fn inCval) out)
fourC = twoC `bind` \two -> ret (two*2)
twoHelloC = twoC `bind` \two ->
helloC `bind` \hello ->
ret $ (show two)++hello
i can have fourC(identity) compiling and working well.
But binds in twoHelloC complain about Int/String type mismatch.
current impl of bind I have:
val twoCont: (Int => Int) => Int =
out => out(2)
val helloCont: (String => String) => String =
out => out("hello")
type Cont[X, R] = (X => R) => R
extension[A, FinalRes] (inCont: Cont[A, FinalRes]) {
infix def bind[B](fn: A => Cont[B, FinalRes]): Cont[B, FinalRes] = {
(out: B => FinalRes) => inCont(inContVal => (fn(inContVal))(out))
}
}
val twoHelloCont: (String => String) => String =
twoCont bind (two =>
helloCont bind (hello => // here it is unhappy to see Cont[String, String]
return_(two.toString + hello)
)
)
Question:
how would you implement infix bind in Scala, and why Haskell typesystem permits twoHelloC to compile? What do i miss here?
thanks
If you have questions what types were inferred in Haskell you can always ask
:t ...in ghciIn Scala you should start with ordinary methods. Verbose translation is
which can be shortened to
Now you can add
extension,infix,Contetc.Is is clear how to finish translation?