Higher-order functions
There is no restriction on functions, which may thus be passed as arguments to other functions. Let us define a function
sigma
that returns the sum of the results of applying a given function f
to each element of a list:let rec sigma f = function
| [] -> 0
| x :: l -> f x + sigma f l;;
val sigma : ('a -> int) -> 'a list -> int =
Anonymous functions may be defined using the
function
construct:sigma (function x -> x * x) [1; 2; 3];;
- : int = 14
Polymorphism and higher-order functions allow defining function composition in its most general form:
let compose f g = function x -> f (g x);; val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b =let square_o_fact = compose square fact;; val square_o_fact : int -> int = square_o_fact 5;; - : int = 14400
Ref: http://caml.inria.fr/about/taste.en.html
Không có nhận xét nào:
Đăng nhận xét