i did pattern matching, , it's working fine:
let rec unzip l = match l |[] -> ([], []) |(x,y)::tail -> let (first, second) = unzip tail in (x::first, y::second)
but how using map or fold right (tips please don't tell me how it)
i thinking along lines of:
let unzip : ('a * 'b) list -> 'a list * 'b list = let (first,second) = map (fun (x,y) -> (x::first, y::second) );;
but getting syntax error
if @ type of list.map
:
# list.map;; - : ('a -> 'b) -> 'a list -> 'b list = <fun>
you'll see returns list. since want return pair of lists, can't use list.map
. can use fold. or call list.map
once each list in pair.
update
let's work list.fold_left
, think little easier.
the essence of fold_left
figure out function 1 step of computation. function takes accumulated answer far, , 1 new element of list. return value new accumulated answer. if can define such function, can fold on input list full answer.
one way @ function appear body of for
statement. body of for
1 step of computation.
let's want add list of integers. desired function takes accumulated answer far (an int), next value list (an int), , returns new accumulated answer (the sum of 2 ints). function folded looks this:
let foldme b = + b
if fold on list of ints sum:
# let foldme b = + b;; val foldme : int -> int -> int = <fun> # list.fold_left foldme 0 [3; 5; 7; 11];; - : int = 26
if wanted reverse list, want function takes answer far (reverse of first part of list), , new element of list, , returns reverse new value added @ beginning. function want looks this:
let foldme2 b = b ::
if fold on list, reverse of list:
# let foldme2 b = b :: a;; val foldme2 : 'a list -> 'a -> 'a list = <fun> # list.fold_left foldme2 [] [4; 5; 6; 7];; - : int list = [7; 6; 5; 4]
if can figure out function 1 step of computation, can figure out how folds. take while @ it.
Comments
Post a Comment