OCaml: replacing items in a list

I am wondering how I can write a function that divides a given list into sublists at a given point, swaps those sublists, and returns the resulting list.

For example:

swap([1;3;5;6],2) => [5;6;1;3]

      

I believe the code I have developed is correct?

let rec swap (l,n) =
let rec loop t (count,laux)  =
            match t with
            |  h::t when count < n -> loop t (count+1, h::laux)
            |  h::t ->   h::t@  List.rev laux
            | []->[]
in
    loop l (0,[]) 

      

;;

+3


source to share


1 answer


You're almost there. The problem is that your function handles the case when the length is l

greater than or equal to n

incorrectly.

The pattern []

does not mean that the input list is empty; this means that we have come to the end of the list. What you should do at this point is to put the battery acc

back in the reverse order.



I'm rearranging the templates a bit so that the basic cases come first:

let rec swap (l, n) =
    let rec loop xs count acc =
            match xs with
            | _ when count = n -> xs @ List.rev acc
            | [] -> List.rev acc
            | h::t -> loop t (count+1) (h::acc)
     in loop l 0 []

      

+3


source







All Articles