简体   繁体   中英

Generalized list printing function in SML

I have to write a function to print a list in SML with the following type signature :

     val printGenList = fn : ('a -> 'b) -> 'a list -> unit

The "printGenList" will take two arguments function f and list l and applies the function f to each element of list l recursively.

Since I am new to ML, I am not able to implement it but I tried this code which is giving the different type signature

     fun printGenList = CONS(fib, fn => printGenList fib fibs);

 where,  fib is
        fun fib a b = CONS(a, fn => fib b (a+b));
 and fibs is
        val fibs = fib 0 1;

What you're trying to do is impossible, ML's type system doesn't support this type of polymorphism. If you Google, there are some printf libraries for SML that show you how to approach this -- for each type t that you want to print, you'll need to define a separate t -> unit function and compose them together.

EDIT: Oh, I see, you're not looking for a function to print lists of any type, you're looking for a higher order function that applies an 'a->'b function to every element of a list... my mistake. This is what you need:

val rec printGenList = 
 fn (f : 'a -> 'b) =>
    (fn [] => ()
    | x::xs => (f(x); printGenList f xs))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM