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

Tuesday, October 8, 2013

A taste of programming in ML

Taking a new course Proglang which started this week. So expect more to follow on what I learn.
(* returns NONE if list is empty, else SOME (maxnumber) *)
fun max(numbers: int list) =
if null numbers
then NONE
else
let val max_tail = max(tl numbers)
in
if max_tail = NONE orelse hd numbers >= valOf max_tail
then SOME (hd numbers)
else max_tail
end;
(* concatenates all strings using separator *)
fun stringjoin(strings: string list, separator: string) =
if null strings
then ""
else if null (tl strings)
then hd strings
else hd strings ^ separator ^ stringjoin(tl strings, separator);
(* date is tuple of form (year, month, day) -> returns boolean *)
fun isLeapYear(date: int*int*int) =
#1 date mod 400 = 0 orelse (#1 date mod 4 = 0 andalso #1 date mod 100 <> 0)
(* filter all even numbers *)
fun filterEven(numbers: int list) =
if null numbers
then []
else if hd numbers mod 2 = 0
then hd numbers :: filterEven(tl numbers)
else filterEven(tl numbers);
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment