首页 > 解决方案 > 那些 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使用它们。

如果有人可以暗示这些功能有多有用,我将不胜感激。

标签: f#

解决方案


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双参数函数的运算符。

请看一下博客,它真的很有帮助!


推荐阅读