Does F# have generic arithmetic support?

后端 未结 4 1486
囚心锁ツ
囚心锁ツ 2020-12-03 03:26

Does F# have the same problem as C# where you can\'t directly use arithmetic operators with generic T types?

Can you write a generic Sum function that would return t

4条回答
  •  醉梦人生
    2020-12-03 04:00

    You could do something like this.

    let inline sum<'a when 'a : (static member (+) : 'a -> 'a -> 'a)> a b =
        a + b
    
    let result = sum 3 4
    

    However if I try let result = sum 3 4 I get the error "type ambiguity inherent in the use of the operator '( + )'"

提交回复
热议问题