generics - 内联映射函数 (Functor)

标签 generics f#

我正在尝试编写一个多态的 map (Functor) 但我遇到了这种类型的错误。

给定以下类型

type Result<'TSuccess, 'TError> = 
    | Success of 'TSuccess 
    | Error of 'TError list
    with 
    member this.map f =
        match this with
            | Success(s) -> Success(f s)
            | Error(e) -> Error e

和这个内联函数

let inline (<!>) (f: ^A -> ^B) (t:^T) = 
    let map' = (^T : (member map : (^A -> ^B) -> ^T) (t, f))
    map'

和这个调用代码

(fun x y -> x + y) <!> (Success 3);;

我收到这个错误

(fun x y -> x + y) <!> (Success 3);;
--------------------------------^
/Users/robkuz/stdin(404,33): error FS0001: 
This expression was expected to have type
 'a -> 'b
but here has type
 int

我不明白为什么会这样? 我没有指定 ^T必须是类型
^T<('a->'b>)>这在 F# 中是不可能的。

顺便说一句。像(fun x -> x + 1) <!> (Success 3)这样的电话将工作正常

最佳答案

也许我遗漏了一些明显的东西,但只要对 <!> 做一个小改动就可以了?

type Result<'TSuccess, 'TError> = 
  | Success of 'TSuccess 
  | Error   of 'TError list
  with 
  member this.map (f : 'TSuccess -> 'T) =
    match this with
    | Success s -> Success (f s)
    | Error   e -> Error e

let inline (<!>) (f : ^A -> ^B) (t : ^T) : ^U =
  let map' = (^T : (member map : (^A -> ^B) -> ^U) (t, f))
  map'

[<EntryPoint>]
let main argv = 
  let w = (fun x y -> x + y) <!> Success 3
  let x = (fun x -> x 2) <!> w
  printfn "%A" x // Prints "Success 5"
  0

关于generics - 内联映射函数 (Functor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37948370/

相关文章:

arrays - 带有协议(protocol)的 Swift 泛型数组

c# - 我是一名 C# 开发人员,我是否应该开始更多地关注 F#

c# - 泛型参数的构造函数要求?

java - 泛型不一致地使用类型?

swift - Swift 2.2+ 中类型的上下文类型推断

f# - 如何在 mono (OS X) 中加载 .fsx 文件,并使用内部类型\函数?

f# - 枚举受歧视的工会

java - 为什么不能在有界通配符泛型中拥有多个接口(interface)?

c# - 在 C# 中正确实现 F# Unit

F# 扩展交错数组类型