Maa*_*mon 3 functional-programming scala
尽管我了解 reader monad 的实现,但我在下面给出了两种最突出的方法
case class Reader[R, A](run: R => A)
def readerMonad[R] = new Monad[({type f[x] = Reader[R,x]})#f] {
def unit[A](a: => A): Reader[R, A] = Reader(_ => a)
override def flatMap[A,B](st: Reader[R, A])(f: A => Reader[R, B]): Reader[R, B] =
Reader(r => f(st.run(r)).run(r))
}
Run Code Online (Sandbox Code Playgroud)
或者更简单
case class Reader[R, A](run: R => A) {
def map[B](f: A => B): Reader[R, B] =
Reader(r => f(run(r)))
def flatMap[B](f: A => Reader[R, B]): Reader[R, B] =
Reader(r => f(run(r)).run(r))
}
Run Code Online (Sandbox Code Playgroud)
我想知道 Reader Monad 和 Function1 之间是否存在内在关系。我一直在准备这里和那里的评论暗示这一点。Reader 根据定义是 Function1 monad 吗?
我不这么认为。但我想在一些帮助下围绕这个概念。
当这些函数是类型 1 时,对函数进行排序是什么意思?
也就是说,您使用一个函数并应用一个返回相同类型函数的函数。我确实认为 Reader 是一种特定的技术,独立于函数是函数 1 的事实。线程化环境槽只是一种选择,如果我们愿意,可以使用 FunctionN 来完成。
只是一种直觉。
编辑1
以下是 scala 中 FP 编程的练习方式:
Hard: To cement your understanding of monads,
give a monad instance for the following type,
and explain what it means.
What are its primitive operations?
What is the action of flatMap? ......
case class Reader[R, A](run: R => A)
object Reader {
def readerMonad[R] = new Monad[({type f[x] = Reader[R,x]})#f] {
def unit[A](a: => A): Reader[R,A]
def flatMap[A,B](st: Reader[R,A])(f: A => Reader[R,B]): Reader[R,B]
}
}”
Run Code Online (Sandbox Code Playgroud)
以及让我不满意的部分答案
// The action of Reader's `flatMap` is to pass the `r` argument along to both the
// outer Reader and also to the result of `f`, the inner Reader. Similar to how
// `State` passes along a state, except that in `Reader` the "state" is read-only.
Run Code Online (Sandbox Code Playgroud)
我理解,因为我可以阅读代码。我认为解释不足以清楚地回答练习的问题。我正在寻找比代码功能的简单描述更一般的东西。
例如,固定类型 R 意味着什么。将作为具有相同输入参数类型的效果函数返回的计算链式计算意味着什么?
Reader[R, A]是一个包装器R => A(所以方法可以只在类内部定义,而不是作为函数的扩展方法)。一个函数f可以被包装到一个阅读器Reader(f),一个阅读器r可以被解包到一个函数r.run。那么Reader[R, A]?R => A是同构。
Reader[R, ?]有一个类型为 class 的实例Monad。
R => ?有一个类型为 class 的实例Monad。
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |