在观看了 John De Goes 的“FP to the Max”(https://www.youtube.com/watch?v=sxudIMiOo68)之后,我想知道以无标记最终模式编写 FP 程序的方法。
假设我有一些用于建模副作用的类型类(以他的Console
例子):
trait Console[F[_]] {
def putStrLn(str: String): F[Unit]
def getStrLn: F[String]
}
你会怎么依赖Console
?
隐式
就像他的视频中展示的那样:
def inputLength[F[_]: Functor: Console]: F[Int] =
Console[F].getStrLn.map(_.length)
优点:函数签名很干净,您可以从 typeclass 自动派生中受益
明确地
通过将实例直接传递给函数:
def inputLength[F[_]: Functor](console: Console[F]): F[Int] =
console.getStrLn.map(_.length)
优点:这使您可以根据需要明确连接依赖项,并且感觉不那么“神奇”
不确定编写此功能的最佳/最惯用的方法是什么,不胜感激。
谢谢!