在 F# 中,如何将类型名称作为函数参数传递? [英] In F#, how to pass a type name as a function parameter?

查看:42
本文介绍了在 F# 中,如何将类型名称作为函数参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to pass a type name (such as int, or string, or even the name of a user-defined type) as a function parameter. Currently I am doing the following:

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# 方式是什么?

But the presence of d above is adventitious. What would be the idiomatic F# way to express the above logic?

预先感谢您的帮助.

推荐答案

你可以使用类型参数:

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

这篇关于在 F# 中,如何将类型名称作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆