lec05 - mapp (fun x -> x*x) il;; (* apply the function f...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
(* implementing map and fold (reduce/accumulate) on 'a list_ type *) type 'a list_ = Nil_ | Cons_ of ('a * 'a list_);; let il : int list_ = Cons_(1,Cons_(2,Cons_(3,Nil_)));; (* [1,2,3] *) (* apply the function f to each element returning a new list * map f [a;b;c] = [(f a); (f b); (f c)] *) let rec map (f: 'a->'b) (x: 'a list_): 'b list_ = match x with Nil_ -> Nil_ | Cons_(h,t) -> Cons_(f(h), map f t);; map string_of_int il;; map (fun x -> x*x) il;; (* Copying a list using map *) let copy l = map (fun x -> x) l (* apply the function f to each element and accumulator, return accumulator * fold_right f [a;b;c] r = f a (f b (f c r)) * also called reduce *) let rec fold_right (f:'a -> 'b -> 'b) (lst: 'a list_) (r:'b): 'b = match lst with Nil_ -> r | Cons_(hd,tl) -> f hd (fold_right f tl r);; List.fold_right;; fold_right;; fold_right (fun x y -> string_of_int(x) ^ " " ^ y) il "" ;; (* defining map in terms of fold_right (extra parens due to parsing error) *) let mapp f l = (fold_right (fun x y -> Cons_((f x),y)) l Nil_);;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: mapp (fun x -> x*x) il;; (* apply the function f to accumulator and each element, return accumulator * fold_left f r [a; b; c] is f (f (f r a) b) c *) let rec fold_left (f: 'a -> 'b -> 'a) (r: 'a) (lst: 'b list_): 'a = match lst with Nil_ -> r | Cons_(hd,tl) -> fold_left f (f r hd) tl;; List.fold_left;; fold_left;; fold_left (fun x y -> x ^ " " ^ string_of_int(y)) "" il;; fold_right (fun x y -> x+y) il 0;; fold_left (fun x y -> x+y) 0 il;; (* map and reverse using fold_left *) let maprev f l = fold_left (fun x y -> Cons_((f y),x)) Nil_ l;; maprev (fun x -> x*x) il;; (* filtering list according to predicate f *) let filter f l = (fold_right (fun x y -> if (f x) then Cons_(x,y) else y) l Nil_);; filter (fun x -> (x / 2)*2 = x) il;; let evens l = filter (fun x -> (x / 2)*2 = x) l;; (* defining length in terms of folding *) let length l = fold_left (fun x _ -> 1 + x) 0 l;; length il;;...
View Full Document

This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell.

Page1 / 2

lec05 - mapp (fun x -> x*x) il;; (* apply the function f...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online