Scheme/ML Comparison

The table below provides several examples written in both ML and Scheme.

ML Code Scheme Code
fun factorial(n) =
    if n = 0 then 1
    else n * factorial(n - 1);
(define (factorial n)
  (if (= n 0)
      1
      (* n (factorial (- n 1)))))
fun range(low, high) =
    if low > high then []
    else low::range(low + 1, high);
(define (range low high)
  (if (> low high)
      ()
      (cons low (range (+ low 1) high))))
fun pairOff([]) = []
|   pairOff([x]) = [[x]]
|   pairOff(x::y::rest) = [x, y]::pairOff(rest);
(define (pair-off lst)
  (cond ((null? lst) ())
        ((= (length lst) 1) (list lst))
        (else (cons (list (car lst) (cadr lst)) (pair-off (cddr lst))))))
fun map(f, []) = []
|   map(f, x::xs) = f(x)::map(f, xs);
(define (mapp f lst)
  (if (null? lst)
      ()
      (cons (f (car lst)) (mapp f (cdr lst)))))
fun filter(f, []) = []
|   filter(f, x::xs) =
        if f(x) then x::filter(f, xs)
        else filter(f, xs);
(define (filterr f lst)
  (cond ((null? lst) ())
        ((f (car lst)) (cons (car lst) (filterr f (cdr lst))))
        (else (filterr f (cdr lst)))))
fun factorial2(n) = 
    if n < 2 then 1
    else reduce(op *, range(2, n));
(define (factorial2 n)
  (foldl * 1 (range 2 n)))
fun f(x, lst1, lst2, lst3) =
    member(x, lst1) orelse (member(x, lst2) andalso not(member(x, lst3)));
(define (f x lst1 lst2 lst3)
  (and (member x lst1) (or (member x lst2) (not (member x lst3)))))
fun sumLengths([]) = 0
|   sumLengths(x::xs) = length(x) + sumLengths(xs);
(define (sumLengths lst)
  (if (null? lst)
      0
      (+ (length (car lst)) (sumLengths (cdr lst)))))
fun sumLengths2([]) = 0
|   sumLengths2(lst) = reduce(op +, map(length, lst));
(define (sumLengths2 lst)
  (foldl + 0 (map length lst)))
val evens = map(fn x => 2 * x, range(1, 10));
(define evens (map (lambda (x) (* 2 x)) (range 1 10)))
val numbers = range(1, 5) @ range(1, 10) @ range(3, 8);
(define numbers (append (range 1 5) (range 1 10) (range 3 8)))


Stuart Reges
Last modified: Wed Nov 4 19:43:39 PST 2009