Created
February 17, 2013 03:40
-
-
Save orb/4970013 to your computer and use it in GitHub Desktop.
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
(* | |
comments on euler 1 in SML | |
http://smlpraxis.com/blog/2013/02/14/multiples-of-3-and-5/ | |
*) | |
fun multiples_of n max = | |
let fun build_multiples current_mult list_so_far = | |
if current_mult >= max | |
then list_so_far | |
else let val next_mult = current_mult + n | |
val updated_list = current_mult :: list_so_far | |
in | |
build_multiples next_mult updated_list | |
end | |
in | |
build_multiples n [] | |
end | |
(* since both lists are ordered, your merge can iterate both lists *) | |
fun union_merge set1 set2 = | |
let | |
fun merge (s1, s2, acc) = | |
case (s1,s2) of | |
([], []) => acc | |
| ([], h2::t2) => merge([], t2, h2::acc) | |
| (h1::t1, []) => merge(t1, [], h1::acc) | |
| (h1::t1, h2::t2) => | |
if h1 = h2 | |
then merge (t1, t2, h1::acc) | |
else if h1>h2 (* since the lists are reverse ordered, take the higher item *) | |
then merge (t1, s2, h1::acc) | |
else merge (s1, t2, h2::acc) | |
in | |
merge (set1, set2, []) | |
end | |
val sum = foldl op+ 0 | |
val result = sum (union_merge (multiples_of 3 1000) | |
(multiples_of 5 1000)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment