我如何拥有一个在F#中返回不同类型的函数? [英] How can I have a function that returns different types in F#?

查看:108
本文介绍了我如何拥有一个在F#中返回不同类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用F#制成了扫描仪.当前,它返回一堆类型为(令牌,字符串)的元组列表.

I've made a scanner in F#. Currently it returns a list of bunch of tuples with type (Token, string).

理想情况下,我想返回一个可能包含不同类型的元组列表.例如:

Ideally I'd like to return a list of tuples that might contain different types. For example:

(Token, string) 
//if it's an identifier

(Token, float)
//if it's a float. 

(Token, int)
//etc

因此,基本上我想返回类型(Token, _),但是我不确定如何指定此类型.现在,它只是出现错误,抱怨类型不匹配.我正在浏览我的书和Wikibook,但是我不确定这叫什么.

So, Basically I'd like to return type (Token, _) but I'm not sure how to specify this. Right now it just has errors complaining of mismatched types. I'm looking through my book, and wikibooks, but I'm not really sure what this is called.

如果这确实不可能,我想稍后可以转换类型,但是我希望可以以这种方式返回东西.

If this really isn't possible, I guess I can convert the types later on, but I was hoping I could just return stuff this way.

推荐答案

在F#中有两种相对简单的方法来处理此问题.一种方法是创建一个有区别的联合:

There are two relatively easy ways to handle this in F#. One would be to create a discriminated union:

type Expression =
| Identifier of string
| FloatValue of float
| IntValue of int
| ...

,然后定义您的函数,使其返回(Token * Expression) list.另一种可能性是将所有内容装箱到一个对象中,然后返回(Token * obj) list.对于列表的生产者来说,这稍微容易一些,但是对于消费者而言,则更为烦人.

and then define your function so that it returns a (Token * Expression) list. The other possibility is to box everything into an object and then return a (Token * obj) list. This is slightly easier for the producer of the list, but much more annoying for the consumer.

这篇关于我如何拥有一个在F#中返回不同类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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