Scheme/OCaml Comparison

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

OCaml Code Scheme Code
let factorial(n) =
    if n = 0 then 1
    else n * factorial(n - 1)
(define (factorial n)
  (if (= n 0)
      1
      (* n (factorial (- n 1)))))
let 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))))
let rec pair_off(lst) =
    match lst with
    | []         -> []
    | [x]        -> [[x]]
    | x::y::rest -> [x; y]::pair_off(rest)
(define (pair-off lst)
  (cond ((null? lst) '())
        ((= (length lst) 1) (list lst))
        (else (cons (list (car lst) (cadr lst)) (pair-off (cddr lst))))))
let rec map(f, lst) =
    match lst with
    | []    -> []
    | x::xs -> f(x)::map(f, xs)
(define (mapp f lst)
  (if (null? lst)
      '()
      (cons (f (car lst)) (mapp f (cdr lst)))))
let rec filter(f, lst) =
    match lst with
    | []    -> []
    | 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)))))
let rec factorial2(n) = 
    if n < 2 then 1
    else reduce(uncurry( * ), range(2, n))
(define (factorial2 n)
  (foldl * 1 (range 2 n)))
let f(x, lst1, lst2, lst3) =
    member(x, lst1) || (member(x, lst2) && not(member(x, lst3)))
(define (f x lst1 lst2 lst3)
  (and (member x lst1) (or (member x lst2) (not (member x lst3)))))
let rec sum_lengths(lst) =
    match lst with
    | []    -> 0
    | x::xs -> List.length(x) + sum_lengths(xs)
(define (sumLengths lst)
  (if (null? lst)
      0
      (+ (length (car lst)) (sumLengths (cdr lst)))))
let rec sum_lengths2(lst) =
    match lst with
    | []    -> 0
    | x::xs -> reduce(uncurry(+), map(List.length, lst))
(define (sumLengths2 lst)
  (foldl + 0 (map length lst)))
let evens = map((fun x -> 2 * x), range(1, 10))
(define evens (map (lambda (x) (* 2 x)) (range 1 10)))
let 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: Tue Feb 13 10:37:08 PST 2024