sml - What does function return when "function times zero" in functional programming? -
i stuck sml assignment. trying create compound function (fun compound n f). it's supposed apply function f on n times example, compound 3 f equal f(f(f(x))). got work except case n zero. asked professor won't tell me direct answer. tried give me hint "what's function times zero?" still can't figure out either. can stackoverflow figure out?
thanks.
my code:
fun compound n f = if n < 2 if n = 0 fn x => f x else fn x => f x else fn x => f(compound (n-1) f(x));
example:
val fnc = fn x => x + 1; (* example function used *) compound 5 fnc(10); (* return 15 correct*) compound 0 fnc(10); (* returns 11, should 10 *)
answer:
fun compound n f = if n < 2 if n = 0 fn x => x else fn x => f x else fn x => f(compound (n-1) f(x));
i won't give final answer because don't upset teachers ;) however, i'll try derivation believe you'll find easy complete.
let's start simple case. let's "reimplement" function application, i.e., let's write function takes function , argument , apply first param second one:
fun apply f = f
let's use contrived function, increments integers, testing:
- fun inc n = n + 1; val inc = fn : int -> int - inc 1; val = 2 : int - apply inc 1; val = 2 : int
now, let's write apply2
, function takes function , argument , applies param function 2 times argument:
fun apply2 f = f (f a)
let's test inc
:
- apply2 inc 1; val = 3 : int
seems working. might expect, we'd implement apply3
, apply4
, on. let's see of them @ once:
fun apply f = f fun apply2 f = f (f a) fun apply3 f = f (f (f a)) fun apply4 f = f (f (f (f a)))
it looks can rewrite later ones in terms of earlier ones:
fun apply2 f = f (apply f a) fun apply3 f = f (apply2 f a) fun apply4 f = f (apply3 f a)
we can rewrite apply
:
fun apply f = f (apply0 f a)
remember previous definition of apply
, they're equivalent:
fun apply f = f
so, should apply0
be?
fun apply0 f = ...
Comments
Post a Comment