Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to implement liftM2 in Scala?
    text
    copied!<p>In Haskell, <code>liftM2</code> can be defined as:</p> <pre class="lang-hs prettyprint-override"><code>liftM2 :: (Monad m) =&gt; (a1 -&gt; a2 -&gt; r) -&gt; m a1 -&gt; m a2 -&gt; m r liftM2 f m1 m2 = do x1 &lt;- m1 x2 &lt;- m2 return $ f x1 x2 </code></pre> <p>I'd like to translate this to Scala. My first attempt was the following:</p> <pre class="lang-scala prettyprint-override"><code>def liftM2[T1, T2, R, M[_]](f: (T1, T2) =&gt; R)(ma: M[T1], mb: M[T2]) : M[R] = for { a &lt;- ma b &lt;- mb } yield f(a, b) </code></pre> <p>This fails in what I guess is the most obvious way possible: "value flatMap is not a member of type parameter M[T1]". Right, I haven't indicated that <code>M[_]</code> is some kind of monad. So the next thing I tried was to define some structural type like:</p> <pre class="lang-scala prettyprint-override"><code>type Monad[A] = { def flatMap[B](f: (A) =&gt; Monad[B]): Monad[B] } </code></pre> <p>... and to have <code>M[A] &lt;: Monad[A]</code>. But that doesn't work, because Scala doesn't have recursive structural types.</p> <p>So the next few things I tried involved gyrations similar to <code>M[A] &lt;: FilterMonadic[A, _]</code>. Those all failed, probably because I wasn't able to figure out the right implicit-fu for <code>CanBuildFrom</code>.</p> <p>The most closely-related question I could find here on StackOverflow was <a href="https://stackoverflow.com/questions/3201577/scala-how-to-define-a-structural-type-that-refers-to-itself">this one</a>, touching both on recursive structural types and how to mimic Haskell's typeclasses in Scala. But that approach requires defining an implicit conversion from each type you care about to the trait defining the typeclass, which seems terribly circular in this case...</p> <p>Is there any good way to do what I'm trying to do?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload