Reputation: 1001
I'm trying to create a list of tuples from two different lists where each head from the two lists will become a tuple(ex: headList1 and headList2 become a tuple), and this continues for each element) and I'm getting type errors in F# and I'm not sure what I'm doing wrong. I tried taking away the parentheses putting in braces etc and still to no avail.
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) and (10,20,30) would become [ (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]
Upvotes: 0
Views: 383
Reputation: 2493
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)]
Upvotes: 2
Reputation: 3784
You can simple use the List.map2
function:
let pairToTuple letterList countList =
List.map2 (fun letter count -> (letter, count)) letterList countList
Or you can write it shorter in F# idioms:
let pairToTuple = List.map2 (fun letter count -> (letter, count))
If your question is an exercise and you don't want to use List.map2
, then:
let rec pairToTuple letterList countList =
match letterList, countList with
| [], _ -> []
| _, [] -> []
| letter :: res1, count :: res2 ->
(letter, count) :: pairToTuple res1 res2
Upvotes: 1