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
(* ('a -> 'b) * 'a list -> 'b list *) | |
fun map(f,xs) = | |
case xs of | |
[] => [] | |
| x::xs' => (f x)::map(f,xs') | |
val x1 = map((fn x => x + 1), [4,8,12,16]) | |
val x2 = map(hd, [ [1,2], [3,4], [5,6,7] ]) | |
(* ('a -> bool) * 'a list -> 'a list *) | |
fun filter(f,xs) = | |
case xs of | |
[] => [] | |
| x::xs' => if f x | |
then x::(filter (f, xs')) | |
else filter(f,xs') | |
fun is_even v = | |
(v mod 2 = 0) | |
fun filter_even xs = filter(is_even, xs) | |
val x3 = filter_even([1,2,3,4,5,6]) | |
(* output of program | |
- use "mapfilter.sml"; | |
[opening mapfilter.sml] | |
val map = fn : ('a -> 'b) * 'a list -> 'b list | |
val x1 = [5,9,13,17] : int list | |
val x2 = [1,3,5] : int list | |
val filter = fn : ('a -> bool) * 'a list -> 'a list | |
val is_even = fn : int -> bool | |
val filter_even = fn : int list -> int list | |
val x3 = [2,4,6] : int list | |
val it = () : unit | |
*) |
No comments:
Post a Comment