Types 如何使函数在fsharp中返回真正不同的类型?
假设有一个用FSharp编写的第三方库,它包含几个泛型类,例如:Types 如何使函数在fsharp中返回真正不同的类型?,types,f#,overloading,return-type,Types,F#,Overloading,Return Type,假设有一个用FSharp编写的第三方库,它包含几个泛型类,例如: 第一种类型 第二个参数是类型('a->'b)的函数 DoWork方法返回类型为FirstType 具有方法DoWork,该方法接受: 第二类型“b”的第一个参数 DoWork方法返回类型为SecondType 具有方法DoWork,该方法接受: 第三种类型的第一个参数(b) DoWork方法返回类型为ThirdType'b)*x:FirstType,静态成员操作。Do:f:('a->'b)*x:SecondType,静
- 第一种类型
- 第二个参数是类型('a->'b)的函数
- 第二类型“b”的第一个参数
- 第三种类型的第一个参数(b)
let Do f x = Ops.Do (f, x)
let result = input |> Do someFunction
如果有人有任何想法或建议,我会很高兴。也许我在某一点上错了。我想这就是你想要做的:
type FirstType<'a> = FirstType of 'a
type SecondType<'a> = SecondType of 'a
type ThirdType<'a> = ThirdType of 'a
type Ops = Ops with
static member ($) (Ops, FirstType a) = fun f -> FirstType (f a)
static member ($) (Ops, SecondType a) = fun f -> SecondType (f a)
static member ($) (Ops, ThirdType a) = fun f -> ThirdType (f a)
let inline Do f x = (Ops $ f) x
let first = FirstType 10
let second = SecondType 12
let third = ThirdType "Hello"
let result1 = Do first (fun x -> "hello" + x.ToString())
let result2 = Do second (fun x -> 2 = 4)
let result3 = Do third (fun x -> x.Length)
type FirstType FirstType(f a)
静态成员($)(操作,第二类型a)=乐趣f->第二类型(f a)
静态成员($)(操作,第三种类型a)=乐趣f->第三种类型(f a)
让内联dofx=(Ops$f)x
设first=FirstType 10
设second=SecondType 12
让第三个=第三个键入“你好”
让result1=dofirst(funx->“hello”+x.ToString())
让结果2=Do秒(乐趣x->2=4)
让result3=dothird(乐趣x->x.Length)
在中查找有关内联和重载的详细信息。似乎您正试图在包装器类上实现一个通用映射函数,这对应于,它有一个函数
fmap
,使用与Do
函数相同的签名,但参数翻转。F#确实支持成员函数的函数重载-我认为这是answer@JohnPalmer谢谢你的评论,我尝试过使用重载的成员函数,并更新了我的问题。有没有可能将咖喱与这些方法结合使用?或者欢迎任何建议。@JohnPalmer我更仔细地查看了我的代码,并通过内联函数实现了我想要的功能。谢谢
let Do f x = Ops.Do f x
let result1 = first |> Ops.Do(fun x -> x + 2)
let result2 = second |> Ops.Do(fun x -> "hello" + x.ToString())
let result3 = third |> Ops.Do(fun x -> x = 1) sq
let Do f x = Ops.Do (f, x)
let result = input |> Do someFunction
type FirstType<'a> = FirstType of 'a
type SecondType<'a> = SecondType of 'a
type ThirdType<'a> = ThirdType of 'a
type Ops = Ops with
static member ($) (Ops, FirstType a) = fun f -> FirstType (f a)
static member ($) (Ops, SecondType a) = fun f -> SecondType (f a)
static member ($) (Ops, ThirdType a) = fun f -> ThirdType (f a)
let inline Do f x = (Ops $ f) x
let first = FirstType 10
let second = SecondType 12
let third = ThirdType "Hello"
let result1 = Do first (fun x -> "hello" + x.ToString())
let result2 = Do second (fun x -> 2 = 4)
let result3 = Do third (fun x -> x.Length)