This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun increment_n_times (n,x) = (* computes n + x *) | |
if n=0 | |
then x | |
else 1 + increment_n_times(n-1,x) | |
fun double_n_times (n,x) = (* computes 2^n * x *) | |
if n=0 | |
then x | |
else 2 * double_n_times(n-1,x) | |
fun nth_tail (n,xs) = (* example 3,[4,8,12,16] -> [16] *) | |
if n=0 | |
then xs | |
else tl (nth_tail(n-1,xs)) | |
(* n_times is a higher-order function which takes a function, an int and a value and | |
it's signature is ('a -> 'a) * int * 'a -> 'a | |
*) | |
fun n_times (f,n,x) = | |
if n=0 | |
then x | |
else f (n_times(f, n-1,x)) | |
fun increment x = x +1 | |
fun double x = x + x | |
val x1 = n_times(double,4,7) | |
val x2 = n_times(increment,4,7) | |
val x3 = n_times(tl, 2, [4,8,12,16]) | |
fun addition (n,x) = n_times(increment, n, x) | |
fun double_n_times (n,x) = n_times(double,n,x) | |
fun nth_tail(n,xs) = n_times(tl, n, xs) | |
(* example of using an anonymous function *) | |
fun triple_n_times (n,x) = n_times((fn x => 3 *x),n,x) | |
(* output of program | |
- use "higherorder.sml"; | |
[opening higherorder.sml] | |
val increment_n_times = fn : int * int -> int | |
val double_n_times = <hidden-value> : int * int -> int | |
val nth_tail = <hidden-value> : int * 'a list -> 'a list | |
val n_times = fn : ('a -> 'a) * int * 'a -> 'a | |
val increment = fn : int -> int | |
val double = fn : int -> int | |
val x1 = 112 : int | |
val x2 = 11 : int | |
val x3 = [12,16] : int list | |
val addition = fn : int * int -> int | |
val double_n_times = fn : int * int -> int | |
val nth_tail = fn : int * 'a list -> 'a list | |
val triple_n_times = fn : int * int -> int | |
val it = () : unit | |
*) |
No comments:
Post a Comment