F#让我这样做吗? [英] Does F# let me do this:
问题描述
我想编写一个带有参数'data'的函数.
I want to write a function that takes an argument 'data'.
我希望函数具有match语句,其中某些匹配项返回一个列表,而其他匹配项返回一个列表的元组-我认为这是不可能的,我也不能返回一个列表的元组或两个列表的元组-函数只能返回一种类型, 是吗?
I want the function to have a match statement where some matches return a list but others return a tuple of lists - I'm thinking this isn't possible nor can I return a tuple of one list or a tuple of two lists - a function can return only one kind of type, yes?
相关的问题-我可以编写一个F#函数来接受一个 单个列表或两个 列表的元组,并且在函数内部使用匹配项来查看实际上传递了哪些?
The related question also - can I write an F# function that can accept either a single list or a tuple of two lists and inside the function use a match to see which of these was actually passed?
K
推荐答案
您可以创建一个有区别的联合,其中一个案例包含一个列表,另一个案例包含两个列表的元组,并且然后返回.遵循这些原则...
You can create a discriminated union where one case holds a single list, and the other case holds a tuple of two lists, and then return that. Something along these lines...
type OneOrTwoLists<'a> =
| OneList of 'a list
| TwoLists of 'a list * 'a list
let producingFn () =
if ... then
OneList(listA)
else
TwoLists(listA, listB)
let consumingFn lists =
match lists with
| OneList theList ->
// do something with it
| TwoLists(listA, listB) ->
// do something with them
这篇关于F#让我这样做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!