F#Monad如何修复数据类型

F#Monad如何修复数据类型,f#,monads,F#,Monads,我正试图用F#编写一个Monad,但我无法编译代码,并且出现错误FS0001 错误:此表达式应具有类型“Result”,但此处具有类型“(Result)->Result f(Success x) |故障->故障 让stringToInt(s:string)= 尝试 设结果=s |>int 成功结果 具有 |_->失败 设i正(i:int)= 如果(i>0),则成功i:Result 否则失败 让toString(i:int)= 尝试 设result=i |>string 成功结果 具有 |_->失

我正试图用F#编写一个Monad,但我无法编译代码,并且出现错误FS0001 错误:此表达式应具有类型“Result”,但此处具有类型“(Result)->Result f(Success x) |故障->故障 让stringToInt(s:string)= 尝试 设结果=s |>int 成功结果 具有 |_->失败 设i正(i:int)= 如果(i>0),则成功i:Result 否则失败 让toString(i:int)= 尝试 设result=i |>string 成功结果 具有 |_->失败 让bindIsPositive=bind isPositive:Result 让bindToString=bindToString:Result 让(>>=)xf=绑定fx 设StrintToIntospositiveIntToString s=stringToInt>>=bindIsPositive>>=bindToString [] 让主argv= 打印fn“10” 设mys=strintToIntispositiveToString“9” Console.WriteLine mys.ToString 0//返回整数退出代码
首先,您的
绑定类型不正确:

your version : Result<'a> -> (Result<'a> -> Result<'b>) -> Result<'b>
typical type : Result<'a> -> ('a -> Result<'b>) -> Result<'b>
执行此操作后,可以定义
bindIsPositive
bindToString
bind
操作现在将函数作为第一个参数,因此这可以工作,但您必须删除类型注释:

let bindIsPositive =  bind isPositive 
let bindToString = bind toString
编写函数时,您可以使用
>=
操作符,或使用普通的F#管道和
绑定
函数:

let strintToIntIsPositiveIntToString x =  x |> stringToInt |> bindIsPositive |> bindToString
let strintToIntIsPositiveIntToString x =  x >>= stringToInt >>= isPositive >>= toString
let bind f x = 
    match x with 
    | Success x -> f x
    | Failure -> Failure
let bindIsPositive =  bind isPositive 
let bindToString = bind toString
let strintToIntIsPositiveIntToString x =  x |> stringToInt |> bindIsPositive |> bindToString
let strintToIntIsPositiveIntToString x =  x >>= stringToInt >>= isPositive >>= toString