简体   繁体   English

如何在F#中使用返回不同类型的函数?

[英]How can I have a function that returns different types in F#?

I've made a scanner in F#. 我用F#制作了扫描仪。 Currently it returns a list of bunch of tuples with type (Token, string). 目前,它返回一组带有类型(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

So, Basically I'd like to return type (Token, _) but I'm not sure how to specify this. 所以,基本上我想返回类型(Token, _)但我不知道如何指定它。 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. 我正在浏览我的书和wikibooks,但我不确定这是什么。

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. 如果这真的不可能,我想我可以稍后转换类型,但我希望我能以这种方式返回东西。

There are two relatively easy ways to handle this in F#. 在F#中有两种相对简单的方法可以解决这个问题。 One would be to create a discriminated union: 一个是创建一个受歧视的联盟:

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

and then define your function so that it returns a (Token * Expression) list . 然后定义您的函数,以便它返回一个(Token * Expression) list The other possibility is to box everything into an object and then return a (Token * obj) list . 另一种可能性是将所有内容放入对象中,然后返回(Token * obj) list This is slightly easier for the producer of the list, but much more annoying for the consumer. 这对于列表的制作者来说稍微容易一些,但对于消费者来说更烦人。

I think that using discriminated union as kvb suggests is the way to go. 我认为使用歧视联盟作为kvb建议是要走的路。 Just to add some more information, when writing scanners in F#, it is common to define a token type Token that lists various types of tokens that may carry additional information like this: 只是为了添加更多信息,在F#中编写扫描仪时,通常会定义一个令牌类型Token ,列出可能带有如下附加信息的各种类型的令牌:

type Token = 
// Some toknes with no additional information
| LParen | RParen | Begin | End
// Some tokens with additional values
| Identifier of string
| IntValue of int
| ...

Then you completely remove the need for representing the value separately from the token and you can work with just Token list . 然后,您完全不需要与令牌分开表示值,您可以使用Token list

作为以前答案的补充,请查看Choice类型(以及Choice1of3等选择案例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM