Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml - Move last element of list to front

First off, I apologize if this is a confusing or backwards way to go about what I want to accomplish, but I'm new to "OCaml style".

I want to take the last element of a list, and move it to the front of the list, shifting all the elements up one.

For example: have [1;2;3;4;5] -> [5;1;2;3;4]

I understand that lists in OCaml are basically linked list, so I plan to recursively iterate through the list, find the last element, and then have that element's tail/remaining list point to the head of the list.

What I'm mainly confused about is how to break the link from the second last element to the last element. In the example above, I want to have the 5 point to the 1, but the 4 to no longer point to the 5.

How do I accomplish this, and is there a simpler way to look at this that I'm completely missing?

like image 251
Rowhawn Avatar asked Dec 22 '22 16:12

Rowhawn


1 Answers

You can't "Break the link" because Ocaml lists are a persistent data-structure. You can't really modify the lists, so you have to produce a new list with the values in the order you want.

let thelist = [1;2;3;4;5] in
let lnewhead = List.hd (List.rev thelist) in
lnewhead :: (List.rev (List.tl (List.rev b)));;

You could also define this in a function:

let flipper = fun thelist -> 
    (List.hd (List.rev thelist)) :: (List.rev (List.tl (List.rev thelist)));;

val flipper : 'a list -> 'a list = <fun>
# flipper([1;2;3;4;5]);;
- : int list = [5; 1; 2; 3; 4]
like image 108
Joshua Smith Avatar answered Jan 02 '23 19:01

Joshua Smith