如何将两个Function0 val合并为一个Function0

时间:2011-06-23 17:07:15

标签: scala scalaz

我想象这样的事情:

def combine[A, B, C](f: (A, B) => C): (M[A], M[B]) => M[C]

MFunction0。在scalaz中这可能吗?

2 个答案:

答案 0 :(得分:1)

import scalaz._; import Scalaz._

def combine[A, B, C, M: Applicative](f: (A, B) => C) = 
   (ma: M[A], mb: M[B]) => (ma |@| mb)(f)

答案 1 :(得分:0)

在标准scala中,它并不难,只需坚持你的签名:

def combine[A,B,C]( f: (A,B) => C ) 
  = ( fA:(()=>A), fB:(()=>B) ) => f( fA(), fB() )

这是一个小例子:

scala> val isProdPositive = combine( (i:Int,d:Double) => i*d > 0.0 )
  isProdPositive: (() => Int, () => Double) => Boolean = <function2>

scala> val f1 = () => 2
  f1: () => Int = <function0>

scala> val f2 = () => -1.5
  f2: () => Double = <function0>

scala> isProdPositive(f1,f2)
  res1: Boolean = false