我正在尝试从两个不同的列表创建一个元组列表,其中两个列表中的每个头都将成为一个元组(例如:headList1和headList2成为一个元组),并且每个元素都将继续),我在F#中出现类型错误,我不确定自己在做什么错。我试着去掉括号内的括号,但仍然无济于事。
let rec pairToTuple letter count = // assume that each list is the same, will return a list with (letter, count) in itself
match letter with
| [] -> [()]
| e1::rest1, e2::rest2 -> let tup = (e1, e2)
tup::(pairToTuple rest1 rest2 )
ex:(a,b,c)和(10,20,30)将变成[(a,10);(b,20);(c,30)]
/home/codio/workspace/program/Program.fs(180,5): error FS0001: This expression was expected to have type ''a list' but here has type ''b * 'c'
[/home/codio/workspace/program/program.fsproj]
答案 0 :(得分:3)
What about List.zip function?
> List.zip ["a"; "b"; "c"; "d"] [1; 2; 3; 4];;
val it : (string * int) list = [("a", 1); ("b", 2); ("c", 3); ("d", 4)]
答案 1 :(得分:1)
您可以简单地使用List.map2
function:
let pairToTuple letterList countList =
List.map2 (fun letter count -> (letter, count)) letterList countList
或者您可以在F#惯用语中将其写得更短:
let pairToTuple = List.map2 (fun letter count -> (letter, count))
如果您的问题是练习,并且您不想使用List.map2
,则:
let rec pairToTuple letterList countList =
match letterList, countList with
| [], _ -> []
| _, [] -> []
| letter :: res1, count :: res2 ->
(letter, count) :: pairToTuple res1 res2