0

So I am given the following question and i am havign an incredibly hard time figuring out how to start... can someone help me ?

So far my references are : https://www.cl.cam.ac.uk/~lp15/MLbook/pub-details.html (Essentially chapter 3)

Write an ML function that takes a list of integer pairs (i.e., (int * int) list) and that returns a list containing the sum of the integers in each pair. For instance, when called on [(1,2), (3,4)], this function should return [3, 7].

sshine
  • 15,635
  • 1
  • 41
  • 66
  • `val f = map op+` is a simple solution to your problem. If this is home work, you're probably to expand out the recursive definition of `map`, though. – Andreas Rossberg Apr 25 '20 at 08:10

1 Answers1

0

Here is how one might get started writing the recursive definition that Andreas Rossberg hints at.

fun f [] = ...
  | f ((x,y)::pairs) = ...

This is one basis for a function f that takes a list of pairs. It uses pattern matching to exhaust all possible input values by first splitting lists into empty and non-empty lists, and further splitting non-empty lists into "a head being a pair of x and y and a tail of remaining pairs beyond the first pair, being pairs.

There are many ways you can write this. Another one is using case-of:

fun f pairs =
    case pairs of
         [] => ...
       | (x,y) :: rest => ...

Here because pairs is all pairs, and the pattern matching in case-of still splits the non-empty list into a head and a tail, I want to avoid overlapping the full input list, pairs, with the remaining pairs beyond the first pair, rest. So I gave them separate names.

It sounds like what would probably benefit you the most at this point is read more of your textbook on pattern matching and ask a tutor of some kind.

sshine
  • 15,635
  • 1
  • 41
  • 66