for-comprehensions: map() and flatMap() with additional parameters

81 views
Skip to first unread message

Martin Senne

unread,
Mar 31, 2014, 5:06:57 PM3/31/14
to scala...@googlegroups.com
Hi ML, hi *,

assuming

trait FunTrait+T] {

  def map[S]( f: T => S )(p: Int) : FunTrait[S]

  def flatMap[S](f: T => FunTrait[S])(q: Int)): FunTrait[S]

}


How do I translate the expression for s1

val t1: FunTrait[Int] = ...
val t2: FunTrait[Int] = ...

val s1 : FunTrait[Int] = t1.flatMap(v1 => t2.map( v2 => v1*v2 )(3))(5)


(which is absolutely valid)

into the appropriate for-comprehension syntax??? Either I'm really blind today or I am totally missing some detail ......

for {
  v1 <- t1
  v2 <- t2
} yield v1*v2


... but where to place to additional params???


Cheers, Martin

Marius Danciu

unread,
Apr 1, 2014, 4:07:26 AM4/1/14
to Martin Senne, scala-user
Well you can have:

trait FunTrait+T] {

  def map[S]
(p: Int)( f: T => S ) : FunTrait[S]

  def flatMap[S]
(q: Int)(f: T => FunTrait[S]): FunTrait[S]

}



and then


for {
  v1 <- t1(3)
  v2 <- t2(5)
} yield v1*v2


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Marius Danciu

unread,
Apr 1, 2014, 4:25:30 AM4/1/14
to Martin Senne, scala-user
Ignore this ... but you should be able to use implicits for p and q params.

Martin Senne

unread,
Apr 1, 2014, 3:30:59 PM4/1/14
to Marius Danciu, scala-user

Hi Marius, hi all,

ya, implicits work, but are not what I really want.

Isn't there a way to solve it without implicits???

Cheers, Martin

Jed Wesley-Smith

unread,
Apr 1, 2014, 5:46:11 PM4/1/14
to Martin Senne, Marius Danciu, scala-user
solve what? what you are doing doesn't really make any sense, and you haven't provided any information as to why you want to do that.

Functor and Monad (essentially `map` and `flatMap`) have laws that your proposed implementation will almost certainly break, specifically composition. If you want to "change the shape" of the container/effect, you need to do so within the body of the function passed to flatMap.

cheers,
jed 

Arya Irani

unread,
Apr 2, 2014, 2:07:29 PM4/2/14
to scala...@googlegroups.com
Your

trait FunTrait[+T] {
  def map[S](f: T => S)(p: Int) : FunTrait[S]

  def flatMap[S](f: T => FunTrait[S])(q: Int)): FunTrait[S]
}


is also roughly equivalent to

trait FunTrait[+T] {
  def map[S](f: T => S): Int => FunTrait[S]
  def flatMap[S](f: T => FunTrait[S]): Int => FunTrait[S]
}


which may make it clearer why it doesn't fit into the for-comprehension.


Reply all
Reply to author
Forward
0 new messages