0

I have written a function that will flip alternate elements in a list, however I have to call it, then call its methods (I'm new to ML so I apologize if I'm using the incorrect terms). I would prefer to just call the function without having to call the methods inside it. This is what I have to do now:

(*3. Flip alternate elements in a list, if n = odd, element n remains at end*)
fun flip nil x = x
  | flip x nil = x
  | flip (x::xs) (y::ys) = x::y::flip xs ys;

fun take l =
    if l = nil then nil
    else hd l::skip (tl l)

and skip l =
    if l = nil then nil
    else take (tl l);

but when I call it to reverse the elements, I have to call it :

flip (skip d) (take d);
flip (skip e) (take e);

Is there any way to call the function as :

flip (d);

If I call flip (d); now, it just prints

val take = fn : ''a list -> ''a list
val skip = fn : ''a list -> ''a list

Thank you all in advance!

EDIT: I should mention d is just a list of ints:

val d = [1,2,3,4];
sshine
  • 15,635
  • 1
  • 41
  • 66
hbteibet
  • 159
  • 1
  • 9

1 Answers1

2

Assuming "flipping alternate elements in a list" means turning [1,2,3,4,5,6] into [2,1,4,3,6,5], and throwing away the last element if the length is odd, then you can achieve this simply by pattern matching in a single function:

fun flip (x::y::xs) = y::x::flip xs
  | flip _ = []

Some feedback on your code snippets:

  • Many of your parentheses are unnecessary.
  • Don't use hd / tl, but rather use pattern matching.
  • The actual flipping takes place in your take and skip.

    Your flip could appropriately be called merge.

  • If this were the case, in order to fix flip so it only takes one argument:

    fun flip xs = merge (skip xs) (take xs)
    

    It is very useful to be able to make helper functions with more arguments and call these.

sshine
  • 15,635
  • 1
  • 41
  • 66