theStig
theStig

Reputation: 610

how to check if list is empty

just started learning sml so excuse me for any discomfort that i may cause.

Okay so here is my function:

fun swapPairsInList [(x,y)]
swapPairsInList: (’x * ’y) list --> (’y * ’x) list

I know how to swap the pairs in the list (recursively) but where i'm having issues is with the base case on when the list is empty (null). How exactly do i check if this list is null? I tried

null [(x,y)]

but that's just throwing back an exception. Should i be using pattern matching to solve this problem?

Upvotes: 2

Views: 5962

Answers (2)

Tayacan
Tayacan

Reputation: 1826

For future reference:

fun swapPairsInList []            = []
  | swapPairsInList ((x,y)::tail) = (y,x) :: swapPairsInList tail

The pattern [] matches the empty list.

Of course, using higher order functions like map and foldl is much nicer.

Upvotes: 3

theStig
theStig

Reputation: 610

Okay so i figured it out, I was attacking the problem from the wrong angle once i looked at the map function located in the ListPair structure

New code:

fun swap (x,y) = (y,x);
fun pairSwap l = map swap l;

Upvotes: 1

Related Questions