【问题标题】:In F#, how to pass a type name as a function parameter?在 F# 中,如何将类型名称作为函数参数传递?
【发布时间】:2013-01-08 18:01:33
【问题描述】:

我想传递一个类型名称(例如int,或string,甚至是用户定义类型的名称)作为函数参数。目前我正在做以下事情:

type IntegerOrIntegerList =
    | Integer of int
    | IntegerList of int list

let f (n : int) (d : 'T) : IntegerOrIntegerList =
    match (box d) with
    | :? int as i -> Integer(n)
    | _ -> IntegerList([0 .. n])

但是上面d 的存在是偶然的。表达上述逻辑的惯用 F# 方式是什么?

提前感谢您的帮助。

【问题讨论】:

    标签: types parameters f#


    【解决方案1】:

    您可以使用类型 arg:

    let f<'T> (n : int) =
      if typeof<'T> = typeof<int> then Integer(n)
      else IntegerList([0 .. n])
    

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      相关资源
      最近更新 更多