If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Saturday, October 12, 2013

Using nested pattern matching (ML)

fun zip3 list_triple =
case list_triple of
([],[],[]) => []
|(hd1:tl1, hd2:tl2, hd3:tl3) => (hd1,hd2,hd3) :: zip3 (tl1,tl2,tl3)
| _ => raise ListLengthMismatch
fun unzip lst =
case lst of
[] => ([],[],[])
|(a,b,c)::tl => let val (l1,l2,l3) = unzip tl
in
(a::l1, b::l2, c::l3)
end
fun nondecreasing xs = (* int list -> bool *)
case xs of
[] => true
| _::[] => true
| head::(neck::rest) => head <= neck andalso nondecreasing (neck::rest)
datatype sign = Positive | Negative | Zero
fun multsign (x1, x2) = (* int * int -> sign *)
let fun sgn x = if x = 0 then Zero else if x > 0 then Positive else Negative
in
case (sgn x, sgn y) of
(Positive, Positive) => Positive
| (Negative, Negative) => Positive
| (Zero, _) => Zero
| (_, Zero) => Zero
| _ => Negative
end
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment