d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Ocaml Swapping 2 Elements In A List?
Add Reply New Topic New Poll
Member
Posts: 24,101
Joined: Nov 8 2007
Gold: 5,561.70
Jul 2 2013 07:26pm
I'm trying to swap two elements in a list, not really sure why mines not working.

The correct implementation should do the following:

list_swap_val ([5;6;7;3],7,5) => [7;6;5;3]
list_swap_val ([5;6;3],7,5) => [7;6;3]

Code
let rec list_swap_val (b, u, v) = fold ((fun (a,y) -> if y == u
then u::a else if y == v
then v::a else y::a), [], b)
;;


Mine code currently does:

list_swap_val([0,1,2,3,4,5,6,7,8], 1, 3) => [8,7,6,3,2,5,4,1,0]

I know that it reverses the list because of the fold, but I can't seem to get it to reverse the correct elements.
Member
Posts: 10,812
Joined: Oct 15 2009
Gold: Locked
Warn: 20%
Jul 3 2013 11:17am
I don't know Ocaml, but if there isn't a built in function for this, you can always do something cheesy like copy the 2 values each to a separate variable, then rebuild/edit the list (like the following pseudo code):

Code
def SwapList (input_list, first_index, second_index):
    x :=  input_list[first_index]
    y := input_list[second_index]
    input_list[first_index] := y
    input_list[second_index] := x
    return input_list


This post was edited by Azrad on Jul 3 2013 11:23am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll