我正在尝试将 Haskell 转换Semigroup
为 Scala。Haskell 代码运行良好,但我无法用 Scala 编写
哈斯克尔:
import Data.Semigroup
newtype Combine a b = Combine { unCombine :: (a -> b) }
instance Semigroup b => Semigroup (Combine a b) where
Combine f <> Combine g = Combine (f <> g)
f = Combine $ \n -> Sum (n + 1)
g = Combine $ \n -> Sum (n - 1)
print (unCombine (f <> g) $ 0) -- Sum 0
print (unCombine (f <> g) $ 10) -- Sum 20
斯卡拉代码
import cats.Semigroup
import cats.instances.all._
trait Combine[A, B] {
def unCombine(a: A): B
}
val f = new Combine[Int, Int] {
override def unCombine(n: Int): Int = n + 1
}
val g = new Combine[Int, Int] {
override def unCombine(n: Int): Int = n - 1
}
implicit val mySemigroup: Semigroup[Combine[Int, Int]] = new Semigroup[Combine[Int, Int]] {
def combine(x: Combine[Int, Int], y: Combine[Int, Int]): Combine[Int, Int] = (x,y) match {
// ???
}
}