问题
I need to write a function which takes input of type (int * int) list
and prints pairs of integers. This function should leverage another function printGenList (takes a function f and a list l and applies f to every element of list recursively) whose code I have written like this -
fun printGenList f l =
if NULL l
then ()
else ( (f (HD l) ); printGenList (f) (TL l) );
and provide an anonymous function (the fn … => … construct) that will do the appropriate pretty printing.
回答1:
The type signature tells you to have a list of pairs of integers. An example of a pair of ints would be (4,1)
. A list of pairs would then be [(a,b),(c,d),...]
, and not, as you've tried, a pair of lists of integers.
I'm sure you're familiar with the (x::xs)
notation, since you seem to understand lists to some degree. If we are to match into pairs we can do it like this: ((n,m)::xs)
. This pattern will bind n and m to the corresponding ints and xs to the rest of the list. Then recursion is straightforward:
fun pInts [] = ()
| pInts ((n,m)::xs) = print ("(" ^ Int.toString n ^ ", " Int.toString m ^ ")";
pInts xs
The important thing to glean from this is that you can bind several variables in a single pattern and use them in your functions. You can even, if you're sure you have more than one element in a list, bind several elements at once:
fun pairs [] = []
| pairs [x] = []
| pairs (x::y::xs) = (x,y) :: pairs xs
回答2:
You should take a look at tuples You actually have to define function with following signature :
fn : (int * int) list -> unit
So the function will be something like:
fun pr(lst :(int * int) list) : unit =
case lst of
[] => ()
|(a,b) :: xs => let
val out = Int.toString a ^ Int.toString b
in
print(out);
pr xs
end
I hope that you get basic idea. Try to improve print formatting!
来源:https://stackoverflow.com/questions/19777651/recursive-function-to-pretty-print-the-elements-of-a-list