【问题标题】:Monadic Reduce in the State Monad状态单子中的单子减少
【发布时间】:2015-12-19 20:47:44
【问题描述】:

我一直在尝试使用返回 State 的函数来减少状态单子中的列表:

def op(t1: T, t2: T): State[S, T] 
val list: State[S, List[T]]

我想减少列表以获得State[S, T]

【问题讨论】:

    标签: scala scalaz scalaz7


    【解决方案1】:

    不可能按照所写的方式安全地执行此操作(如果列表为空会发生什么情况?),但如果您有 op 的标识元素,则可以使用来自 FoldablefoldLeftM

    list.flatMap(_.foldLeftM[({ type L[x] = State[S, x] })#L, T](opId)(op))
    

    你也可以这样写:

    list.flatMap {
      case h :: t => t.foldLeftM[({ type L[x] = State[S, x] })#L, T](h)(op)
      case Nil => ???
    }
    

    不幸的是,在这两种情况下,类型参数都是必需的(类型推断在这里不起作用),所以如果你经常做这种事情,你可能想要定义一个类型别名并避免使用类型 lambda。

    【讨论】:

    • 我猜,也可以使用不安全的变体:list.flatMap(l => l.tail.foldLeftM(l.head)(op))
    • @Kolmar 如果你足够关心安全以忍受 state monad 这不太可能是你会选择做的事情。
    • @TravisBrown 完美运行,非常感谢。我实际上非常接近解决方案,但尝试使用类型别名而不是类型 lambda 来解决类型推断问题。由于缺少我的类型别名的 Monad 证据,编译失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2017-11-27
    • 1970-01-01
    • 2019-12-13
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多