0

I am trying to write a function to swap a pair of tuples inside of a list like this:

- pairSwap [(1, 2), (3, 4), (5, 6);
 [(2,1),(4,3),(6,5)]

I am having a hard time figuring out what I am doing wrong with my syntax while declaring the function. This is what I have so far:

fun pairSwap ((a : 'a, b: 'a) list) : (('a, 'a) list) = 
...
;

Where am I going wrong?

Edit: Solution

fun pairSwap (t : ('a * 'a) list) : ('a * 'a) list = 
  if null t
    then []
  else
    let
      val v = hd t
    in
      (#2 v, #1 v)::pairSwap (tl t)
    end
;
Jordan
  • 75
  • 1
  • 5
  • This is not a dupe of the linked question: that one is about a function that maps e.g. `[1,2,3,4]` to `[2,1,4,3]`, whereas this one is about a function that maps e.g. `[(1,2),(3,4)]` to `[(2,1),(4,3)]`. – ruakh Jan 13 '18 at 22:09
  • No, not exactly, but both the title of that question and the answers given would also describe this problem. – sshine Jan 22 '18 at 11:16

2 Answers2

1

You need to pull the variable out of the pair type annotation:

fun pairSwap (arg : ('a * 'b) list) : ('b * 'a) list = ...;

Note that I've also changed it from what you had to what the title requested: ('a * 'a) list -> ('a * 'a) list to ('a * 'b) list -> ('b * 'a) list

Matt
  • 4,029
  • 3
  • 20
  • 37
1

Since you have provided a solution in the meantime, here is some feedback on it:

  • You don't really need the type annotations. You can let type inference do the work.

    fun pairSwap t = ...
    
  • You can use null, hd and tl, but consider pattern matching:

    fun pairSwap [] = []
      | pairSwap ((x,y)::ps) = (y,x)::pairSwap ps
    

    This also makes the let-expression redundant.

  • As Matt points out, the type for this function is ('a × 'b) list → ('b × 'a) list, which means you can also swap pairs where the left side has a different type ('a) than the right side ('b), e.g.:

    - pairSwap [("hello",42),("world",43)];
    val it = [(42,"hello"),(43,"world")] : (int * string) list
    
sshine
  • 15,635
  • 1
  • 41
  • 66
  • Thanks for the feedback. This is my first time playing with sml for one of my classes so I was encouraged to use types to help transition towards sml syntax. I will keep this in mind next time. – Jordan Jan 12 '18 at 18:29