在scala中堆叠Monad变形金刚
发布时间:2020-12-16 18:47:30 所属栏目:安全 来源:网络整理
导读:我试图以一种 haskell方式堆叠 scalaz的monad transfromers: statyReader :: (MonadReader Int m,MonadState Int m) = m Int 斯卡拉: def statyReader[F[_]](implicit r: MonadReader[F,Int],s: MonadState[F,Int]): F[Int] = for { counter - s.get secre
我试图以一种
haskell方式堆叠
scalaz的monad transfromers:
statyReader :: (MonadReader Int m,MonadState Int m) => m Int 斯卡拉: def statyReader[F[_]](implicit r: MonadReader[F,Int],s: MonadState[F,Int]): F[Int] = for { counter <- s.get secret <- r.ask _ <- s.put(counter + secret) } yield counter 它用1隐式传递编译,但不用2: Error:(13,18) value flatMap is not a member of type parameter F[Int] counter <- s.get ^ Error:(14,18) value flatMap is not a member of type parameter F[Int] secret <- r.ask ^ Error:(15,21) value map is not a member of type parameter F[Unit] _ <- s.put(counter + secret) ^ 为什么会这样?我的猜测是编译器现在混淆了它应该选择的“F [_]”的monadic实例(MonadReader和MonadState都扩展了Monad [F [_]).这是一个正确的猜测吗? 怎么克服这个? 解决方法
这不是一个真正的答案,但也许有点帮助.
我觉得你是对的;似乎编译器无法统一两个参数的F [_]类型(我猜因为它是具有多个可能实例而不是具体类型实例的高级类型)到monad类型.编译使用单独的参数列表,因为类型统一仅在参数列表中发生.它可以进一步说明如下: def statyReader[F[_]](implicit r: MonadReader[F,Int]): F[Int] = statyReader2(r,s) def statyReader2[F[_]:Monad](r: MonadReader[F,Int]): F[Int] = for { counter <- s.get secret <- r.ask _ <- s.put(counter + secret) } yield counter Error: ambiguous implicit values: both value s of type scalaz.MonadState[F,Int] and value r of type scalaz.MonadReader[F,Int] match expected type scalaz.Monad[F] 显然,作为一种解决方法,您可以使用两个参数列表来选择要使用的monad: def statyReader[F[_]](implicit r: MonadReader[F,Int]): F[Int] = statyReader2(r)(s) def statyReader2[F[_]](r: MonadReader[F,Int])(implicit s: MonadState[F,Int]): F[Int] = for { counter <- s.get secret <- r.ask _ <- s.put(counter + secret) } yield counter (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |