Search code examples
listf#cons

Pattern matching x::xs not splitting list accordingly in F#?


I'm new to F# and I'm trying to write a method split that splits a list into 2 pieces. It takes a tuple with the first element being the number of elements to split and the second element is the list . For example, split (2, [1;2;3;4;5;6]) should return ([1;2], [3;4;5;6]),

This is what I have so far, but for some reason it is returning the second element of the tuple as the original list without the head. I don't understand this because I thought that x::xs automatically makes x the head element and xs the rest of the list, which would mean that each recursive call is taking the tail of the previous list and chopping off the first term.

let rec split = function
   |(n, []) -> ([], [])
   |(0, xs) -> ([], xs)
   |(n, x::xs) -> let temp = x :: fst (split(n-1, xs))
                  (temp, xs);;

Solution

  • The problem is on this line:

    (temp,xs);;
    

    here in your example, xs will always be [2;3;4;5;6] as long as n>0

    You need to get the second element of the list with something like

    |(n,x::xs) ->
        let a,b = split (n-1,xs)
        (x::a,b)