How to make a function to return really different types in fsharp?

青春壹個敷衍的年華 提交于 2019-12-05 12:19:03

I think this is what you are trying to do:

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)

Find more about inline and overloading in these posts. It seems you are trying to implement a generic map function over your wrapper classes, this correspond to the Functor Typeclass in Haskell, which has a function fmap, with the same signature as your Do function but with the arguments flipped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!