Skip to content

Instantly share code, notes, and snippets.

@sshine
Created October 23, 2011 15:02
Show Gist options
  • Save sshine/1307449 to your computer and use it in GitHub Desktop.
Save sshine/1307449 to your computer and use it in GitHub Desktop.
Standard ML: Imperative vs. functional
infixr 0 $
fun f $ x = f x
val concat = List.concat
fun good_cartesian_product (xs, ys) =
concat (map (fn y => map (fn x => (x,y)) xs) ys)
fun evil_cartesian_product (xs', ys') =
let
val result = ref []
val xs = ref xs'
val ys = ref ys'
in (
while not (null !ys) do (
while not (null !xs) do (
result := !result @ [(hd (!xs), hd (!ys))];
xs := tl (!xs)
);
xs := xs';
ys := tl (!ys)
);
!result
)
end
(* renaming some operations *)
val get = !
val set = op:=
val empty = null
fun evil_cartesian_product (xs', ys') =
let
val result = ref []
val xs = ref xs'
val ys = ref ys'
in (
while not(null(get(ys))) do (
while not(null(get(xs))) do (
set(result, get(result) @ [(hd(get(xs)), hd(get(ys)))]);
set(xs, tl(get(xs)))
);
set(xs, xs');
set(ys, tl(get(ys)))
);
get(result)
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment