I need to write some function NTimesComposition(f:(int * int -> int), n:int) which receives some function f and integer n and after doing composition of f, n times, like this f(x,(f(x,f(x,y)))) <- (here for example n = 3) I began to write it on smlnj, but it seems more complicated than I thought thanks in advance for any idea:
开发者_JS百科NTimesComposition(f:(int * int -> int), n:int)
if n = 1 then fn(x,y) => f(x, y ) else NTimesComposition...//here I'm stuck, must be recurstion
You already got it for n = 1 and you most likely just forgot to pass the (x, y)
in the recursive call for n > 1. Obviously here it needs to be something of the form fn (x,y) => f (x, ...)
where the ...
part is where your recursive calls is going to be.
If you had forgot the (x,y)
in the recursive part making it fn (x,y) => NTimesComposition (f, n-1)
then you would end up building a chain of anonymous functions as "long" as your argument n
describes. That would result in a different type of your NTimesComposition
function depending on what n
you supply which is not valid due to the way SML's type system works (Hindley-Milner).
The following two functions will do the job for you
fun foo (f, 1) = (fn xy => f xy)
| foo (f, n) = (fn (x,y) => f(x, foo (f, n-1) (x,y)))
and
fun baz (f, 1) xy = f xy
| baz (f, n) (x,y) = f(x, foo (f, n-1) (x,y))
where the first resembles your code the most using the anonymous function.
精彩评论