f# - 那些 F# 函数应该做什么?
问题描述
这些天学习F#,我注意到在一些类似这个或那个的库中, 有一些类似的函数,这些函数在F#中似乎很常见,但无法真正破译它们,它们在做什么,它们有什么用?
let ap x f =
match f, x with
| Ok f , Ok x -> Ok (f x)
| Error e , _ -> Error e
| _ , Error e -> Error e
let inline (<*>) f x = ap x f
let inline (<!>) f x = Result.map f x
let inline lift2 f a b = f <!> a <*> b
即使将评论与他们汇总并不能真正帮助我理解:
/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let ap x f =
match f,x with
| Ok f , Ok x -> Ok (f x)
| Error e , _ -> Error e
| _ , Error e -> Error e
/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let inline (<*>) f x = ap x f
/// Infix map, lifts a function into a Result and applies it on the given result.
let inline (<!>) f x = Result.map f x
/// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
let inline lift2 f a b = f <!> a <*> b
我什至没有看到如何使用它们的示例,也不知道为什么inline
使用它们。
如果有人可以暗示这些功能有多有用,我将不胜感激。
解决方案
Scott Wlaschin 的F# for fun and profit ( https://fsharpforfunandprofit.com ) 有一系列Map and Bind and Apply,哦,天哪!(https://fsharpforfunandprofit.com/posts/elevated-world-7)应该能够对此进行更多说明。关于您的特定问题:
<!>
是将map
函数f
和参数应用于x
要映射的数据结构的元素的运算符,或者换句话说,将函数提升到数据结构的领域,在这种情况下是Result
类型。<*>
是ap
(apply) 运算符,它将包装在提升值内的函数解包为提升函数。lift2
基本上是map
双参数函数的运算符。
请看一下博客,它真的很有帮助!
推荐阅读
- python-3.x - Python初学者有一个基本问题:如何正确调用类和方法?
- angular - 如何在 Firebase 云函数和 Angular 之间共享 typescript 类
- python - 我真的需要这个python代码解释
- python - aiohttp logging:如何区分不同请求的日志消息?
- python - 如何计算窗口内的平均值,其中窗口的范围取决于列的值?
- sql - sql - 获取 2 个子查询的最小值
- reactjs - 材质 UI DatePicker 设置为必需
- sockets - 在 WebRTC 的上下文中,一般如何建立对等 (P2P) 套接字连接?
- python - 在 HDP 集群中使用 HDFS3 库连接 Namenode 时出错
- excel - 由于缓冲区问题,剑道导出到 excel 失败