Search code examples
listfunctiontuplessmlml

SML Function and Tuples


The SML function map takes a function and a list and it applies the function on the elements of the list.

The function map, which has the following type, is both polymorphic and higher order function.

fun map f [] = [] | map f (x::xs) = (f x)::(map f xs) 
val it = fn : (’a -> ’b) -> ’a list -> ’b list

Write another function mymap that takes two functions f and g and a list of 2-element tuples.

It applies f on the first element of the tuples and it applies g on the second element of the tuples.

For example:

- fun sqr x = x* x;
val sqr = fn : int -> int
- fun cube x:real = x*x*x;
val cube = fn : real -> real
- mymap sqr cube [(1,2.0),(2,3.0),(3,4.0),(4,5.0)];

I don't know how to used first function map and i need hint for second function mymap


Solution

  • You could try:

    fun mymap f g l =
        let 
           fun  f1 f (h,h1) = (f(h),h1)
    
           fun  g1 g (h,h1) = (h,g(h1))
        in
            map (g1 g) (map (f1 f) l)
        end
    

    We define two functions f1,g1 which have tuple as argument so that we could use map with f1 and list of tuples and same for g1.

    Example:

    - mymap sqr sqr [(4,9),(4,16),(9,4)];
    val it = [(16,81),(16,256),(81,16)] : (int * int) list