我需要在F#中创建一个函数以将两个列表中的元素配对在一起(请参见下图中的(ii)):我实际上不确定要问的是什么:我是否需要创建一个包含两个元素的函数?列出并返回一个对的列表,其中结果列表中的ith个元素是一个对,其中对中的第一个元素是第一个列表中的ith元素,而对中的第二个元素是第二个列表中的ith个元素?我不明白这*
是什么意思val pairlists :'a list * 'b list -> ('a * 'b)list
如果那是我应该做的,那么这就是我尝试过的:
let pairlists (l : 'a list) (m : 'b list) =
if l.Length <> m.Length then
failwith "the two lists does not have the same size"
else
[for i in 1 .. l.Length do
yield (l.Head,m.Head)
]
我不确定该怎么做,因为我不知道该如何遍历列表?救命
您可以通过模式匹配来遍历列表,这是使用match ... with
表达式完成的。
例如:
f l =
match l with
| head :: tail -> "This list has at least one element!"
| _ -> "This list is empty"
> f [1]
> "This list has at least one element!"
> f [1; 2]
> "This list has at least one element!"
> f []
> "This list is empty"
在您的情况下,可能有几种可能性:两个列表都是空的,一个列表是空的,另一个列表不是,或者两个都有至少一个元素:
pairlists l m =
match l, m with
| (lhead :: ltail), (mhead :: mtail) -> // both non-empty
| [], (mhead :: mtail) -> // first list empty, second is not
| (lhead :: ltail), [] -> // second is empty, first is not
| [], [] -> // both are empty
现在,您需要做的就是确定这四种情况中每种情况下函数的结果,然后将其写下来。
我不会给您完整的答案,因为这显然是家庭作业,但这是另一个提示:将两个非空列表配对意味着将其头部(即第一个元素)配对,然后将其尾部配对,然后将两者连接在一起。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句