I’m trying to split an F# list into two by taking alternate elements. Here’s my attempt:
let split l =
let rec loop l isEven result1 result2 =
match l with
| [] -> result1 result2
| [head::tail] when isEven -> loop tail (not isEven) head::result1 result2
| [head::tail] -> loop tail (not isEven) result1 head::result2
loop l false [] []
That gives me an error:
Program.fs(5,39): error FS0001: Type mismatch. Expecting a
'a
but given a
'b -> 'a list
The resulting type would be infinite when unifying ''a' and ''b -> 'a list'
I don’t see how it can be infinite, and I don’t understand why it thinks I’m giving it a function from ‘b to ‘a list. Could somebody tell me where I’m going wrong?
Here’s a fixed version:
[]), I added a comma since the theloopfunction needs to return the values as a tuple. Without the comma, you’re basically treatingresult1like a function and applyingresult2to it.[]) but in the other cases, you don’t use the brackets — just the cons (::) pattern.head :: resultin parenthesis, otherwise F# reads the code as if you wrote this:(loop tail (not isEven) head) :: (result1 result2).Oh, and if you want the lists you’re returning to be in the same order as the original list, you need to use List.rev when you return the lists, like this:
Finally, here’s a slightly simplified version of your function — you don’t really need the
isEvenparameter to make the function work. Instead, you just try to keep the lists the same length: