# I must exchange the position of 2 values of a list

Hello, I am in computer license and I have a function that I understand what it does but I can not write it, it is necessary I exchange between 2 value of a list, we can give any index that will exchange with the index 0 example: [1;2;3;4] 3 so the value of the index 3 which is 4 will exchange with the value of the index 0 which will exchange with the value of the index 0 which gives [4;2;3;1]
enunciate:
Write a retourner_spatule function: a’ list → int → a’ int
retourner_spatule l i returns the list l, in which the pancakes located at the spatula (therefore from the index 0 to the index i included) have been returned.
You have the right to call the concat function of the sorting count only once

This isn’t a place to solve your homework problems for you, but I’ll leave a couple of hints:
You want to traverse the list counting down the index as you go, while keeping the list head around, then when you reach 0, you place the head you kept around in place of your current head, and you propagate your current head out somehow. The less efficient but easier route would be to take n, drop n, swap heads, then append the resulting lists:

``````take 3 [1; 2; 3; 4]      ⇒ [1; 2; 3]
drop 3 [1; 2; 3; 4]      ⇒ [4]
swap_heads [1; 2; 3] [4] ⇒ [4; 2; 3], [1]
append [4; 2; 3] [1]     ⇒ [4; 2; 3; 1]
``````

what’s left for you to do is implement the missing functions.

instead of showing you the desired solution, here’s something that is absolutely not the answer you want to submit, using effects for fun, in the spirit of the recent release :3

``````open Effect
open Effect.Deep

type _ Effect.t += Switch : int -> int Effect.t

let rec switcharoo xs n = match xs with
| [] -> [] (* 1 *)
| x :: xs ->
if n > 0
then x :: switcharoo xs (pred n)
else perform (Switch x) :: xs

let switcharoo xs n = match xs with
| [] -> []
| x::xs ->
let runner = try_with (switcharoo xs) (pred n)
and handler (type a) (e : a Effect.t) = match e with
| Switch n ->
Some begin fun (k : (a, _) continuation) ->
n :: continue k x
end
| _ -> None
in
runner { effc = handler }
``````

`(* 1 *)`: you could check `n > 0` and perform a different effect that says you asked for a value that is greater than or equals the list length, but the problem statement doesn’t define what the error path is like, and undefined behaviour means freedom in my book :3
So instead, I chose to interpret `switcharoo [x] 100` as “discard x”.

1 Like

Well, except that the other thread is in French, and this one was made to reach is larger audience, so one could argue it’s not really a duplicate.