ML Dialects and Friends: OCaml, F#, Scala, Haskell

a side-by-side reference sheet

grammar and invocation | variables and expressions | arithmetic and logic | strings | dates and time | arrays | lists | tuples | dictionaries | functions | execution control | exceptions | concurrency | file handles | files | directories | processes and environment | libraries and namespaces | user-defined types | objects | polymorphism | net and web | unit tests | debugging and profiling | repl

ocaml f# scala haskell
version used
 
4.0 F# 3.0
Mono 3.2
2.9 7.4
show version
 
$ ocaml -version $ fsharpi --help $ scala -version $ ghc --version
grammar and invocation
ocaml f# scala haskell
interpreter
 
$ echo 'print_endline "hello"' > hello.ml

$ ocaml hello.ml
$ cat <<EOF > hello.fs
module hello
let main = printfn "hello"
EOF

$ fsharpi --quiet --exec hello.fs
$ echo 'println("hello")' > hello.scala

$ scala hello.scala
$ echo 'main = putStrLn "hello"' > hello.hs

$ runghc hello.hs
shebang $ cat <<EOF > hello.ml
#!/usr/bin/env ocaml

print_endline "hello";;
EOF

$ chmod +x hello.ml
$ ./hello.ml
$ cat <<EOF > hello.fs
#light (*
  exec fsharpi --exec $0 --quiet
*)

module hello

printfn "hello"
EOF

$ chmod +x hello.fs
$ ./hello.fs
$ cat <<EOF > hello.scala
#!/bin/sh
exec scala $0 $@
!#

println("hello")
EOF

$ chmod +x hello.scala
$ ./hello.scala
$ cat <<EOF > hello.hs
#!/usr/bin/env runghc

main = putStrLn "hello"
EOF

$ chmod +x hello.hs
$ ./hello.hs
bytecode compiler and interpreter $ echo 'print_endline "hello";;' > hello.ml
$ ocamlc -o hello hello.ml
$ ocamlrun hello
$ echo 'printfn "hello"' > hello.fs
$ fsharpc hello.fs
$ mono hello.exe
$ cat <<EOF > Hello.scala
object Hello {
  def main(args: Array[String]) {
    println("hello")
  }
}
EOF

$ scalac Hello.scala
$ scala Hello
none
native compiler $ echo 'print_endline "hello";;' > hello.ml
$ ocamlopt hello.ml -o hello
$ ./hello
none none $ echo 'main = putStrLn "hello"' > hello.hs
$ ghc -o hello hello.hs
$ ./hello
library which is always imported Pervasives Core java.lang
scala
Prelude
statement terminator ;; ;; ; or sometimes newline next line has equal or less indentation, or ;
blocks ( expr ; )
begin expr ; end
( expr ; )
begin expr ; end
{ } offside rule or { }
end-of-line comment none // comment // comment -- comment
multiple line comment (* comment
another comment
*)
(* comment
another comment
*)
/* comment
another comment
*/
{- comment
another comment
-}
variables and expressions
ocaml f# scala haskell
write-once variable
 
let n = 1 + 2;; let n = 1 + 2 // evaluates 1 + 2 once:
val n = 1 + 2

// evaluates 1 + 2 each time n is used:
def n = 1 + 2
n = 3
modifiable variable let n = ref 3;;
n := 4;;
!n + 7;;
let n = ref 3
n := 4
!n + 7
var n = 3
n = 4
n + 7
n <- return 3
unit type and value unit
()
unit
()
Unit
()
()
()
conditional expression let n = -3;;
let absn = if n < 0 then -n else n;;
let n = -3
let absn = if n < 0 then -n else n
val n = -3
if (n < 0) -n else n
n = -3
let absn = if n < 0 then -n else n
branch type mismatch (* compilation error: *)
if true then "hello" else 3;;
(* compilation error: *)
if true then "hello" else 3
// expression has type Any:
if (true) { "hello" } else { 3 }
-- compilation error:
if True then "hello" else 3
null
 
None None

Also this value returned by .NET library functions. It has a type distinct from None:
null
null Nothing
nullable type type list_option_int = int option list;;

let list = [Some 3; None; Some (-4)];;
val list = List(Some(3), null, Some(-4)) list = [Just(3), Nothing, Just(-4)]
null test match foo with
  | None -> true
  | _ -> false;;
coalesce match foo with
  | None -> 0
  | Some n -> n;;
import Data.Maybe

let foo = Just(3)
raises exception if Nothing:
fromJust foo

let intId x = x
evaluates to 0 if Nothing:
maybe 0 intId foo
nullif match foo with
  | -999 -> None
  | n -> Some n;;
expression type declaration float 1 float 1 1: Double 1 :: Double
let ... in ... let z =
  let x = 3.0 in
  let y = 2.0 *. x in
  x *. y;;
let z =
  let x = 3.0 in
  let y = 2.0 * x in
  x * y
val z = {
  val x = 3.0
  val y = 2.0 * x
  x * y
}
z = let x = 3.0
        y = 2.0 * x
    in x * y
where none none none z = x * y
  where x = 3.0
        y = 2.0 * x
arithmetic and logic
ocaml f# scala haskell
boolean type
 
bool bool Boolean Bool
true and false
 
true false true false true false True False
logical operators && || not && || not && || ! && || not
relational operators = <> < > <= >= = <> < > <= >= == != < > <= >= == /= < > <= >=
min and max min 1 2
max 1 2
min 1 2
max 1 2
math.min 1 2
math.max 1 2
min 1 2
max 1 2
integer type int

other integer types:
int32 int64 nativeint
int

other integer types:
int32 int64 nativeint
type of integer literals:
Int
other modular types:
Byte Short Long
arbitrary precision type:
BigInt
Integer
integer literal int, int64, and nativeint literals:
12 12L 12n

literals can contain underscores:
1_000_000

this parses as an expression:
-4
-4 -4 an expression, not a literal:
-4
float type float float type of float literals:
Double
other types:
Float
Double
integer operators + - * / mod
mod is an infix operator
+ - * / % + - * / % + - * div rem
div and rem are functions, not infix operators
float operators
 
+. -. *. /. + - * / + - * / + - * /
add integer and float float 3 +. 7.0 float 3 + 7.0 3 + 7.0 3 + 7.0
integer division
and remainder
7 / 3
7 mod 3
7 / 3
7 % 3
7 / 3
7 % 3
div 7 3
rem 7 3
integer division by zero raises Division_by_zero System.DivideByZeroException java.lang.ArithmeticException Exception: divide by zero
float division
 
float 7 /. float 3 float 7 / float 3 (7: Double) / 3 7 / 3
float division by zero infinity nan or neg_infinity infinity nan or neg_infinity evaluates to Infinity, NaN, or -Infinity, values which do not have literals evaluates to Infinity, NaN, or -Infinity, values which do not have literals
power 2.0 ** 32.0 2.0 ** 32.0 math.pow(2, 32) 2 ** 32

-- syntax error if exponent not an integer:
2 ^ 32
sqrt
 
sqrt 2.0 sqrt 2.0 math.sqrt(2) sqrt 2
sqrt -1 sqrt (-1.0):
nan
nan math.sqrt(-1) evaluates to NaN, a value which has no literal sqrt (-1) evaluates to NaN, a value which has no literal
transcendental functions exp log
sin cos tan
asin acos atan atan2
exp log
sin cos tan
asin acos atan atan2
math.exp math.log
math.sin math.cos math.tan
math.asin math.acos math.atan math.atan2
exp log
sin cos tan
asin acos atan atan2
transcendental constants 4.0 *. atan 1.0
exp 1.0
System.Math.PI
System.Math.E
math.Pi
math.E
pi
exp 1
float truncation truncate 3.14
none
floor 3.14 returns float
ceil 3.14 returns float
truncate 3.14
round 3.14
floor 3.14 returns float
ceil 3.14 returns float
??
3.14.round
3.14.floor returns Double
3.14.ceil returns Double
truncate 3.14
round 3.14
floor 3.14
ceiling 3.14
absolute value
and signum
abs (-7)
abs_float (-7.0)
no signum
abs -7
abs -7.0
sign -7
sign -7.0
math.abs(-7)
math.signum(-7)
abs (-7)
signum (-7)
integer overflow modular arithmetic modular arithmetic modular arithmetic for all types except BigInt has arbitrary length integers
float overflow infinity infinity evaluates to Infinity, a value which has no literal evaluates to Infinity, a value which has no literal
arbitrary length integer open Big_int;;

let n = big_int_of_int 7;;
let m = big_int_of_int 12;;
// System.Numerics.BigInteger:
let n = 7I
let m = 12I
val n = BigInt(7)
val m = BigInt(12)
-- Integer is arbitrary length type:
let n = 7
let m = 12
arbitrary length integer operators add_big_int n m
sub_big_int n m
mult_big_int n m
div_big_int n m (* quotient *)
mod_big_int n m

eq_big_int n m
lt_big_int n m
gt_big_int n m
le_big_int n m
ge_big_int n m
n + m
n - m
n * m
n / m
n % m

n = m
n < m
n < m
n <= m
n >= m
n + m
n - m
n * m
n / m
n % m

n == m
n < m
n < m
n <= m
n >= m
n + m
n - m
n * m
div n m
mod n m

n == m
n < m
n < m
n <= m
n >= m
rational type Ratio Integer
rational construction import Data.Ratio

1 % 7
rational decomposition import Data.Ratio

numerator (1 % 7)
denominator (1 % 7)
complex type Complex.t Complex Double
complex constants Complex.zero
Complex.one
Complex.i
complex operators Complex.add z w;;
Complex.sub z w;;
Complex.mul z w;;
Complex.div z w;;
complex construction {Complex.re=1.0; Complex.im=2.0} System.Numerics.Complex(1.0, 2.0) import Data.Complex

1 :+ 2.0
complex decomposition let z = {Complex.re=1.0; Complex.im=2.0};;

z.Complex.re;;
z.Complex.im;;
Complex.arg z;;
Complex.norm z;;
Complex.conj z;;
import Data.Complex

realPart (1 :+ 2)
imagPart (1 :+ 2)
phase (1 :+ 2)
magnitude (1 :+ 2)
conjugate (1 :+ 2)
random number
uniform int, uniform float, normal float
Random.int 100
Random.float 1.0
none
let rnd = System.Random()

rnd.Next(0, 100)
rnd.NextDouble()
none
import scala.util.Random

val rnd = Random

rnd.nextInt(100)
rnd.nextDouble
rnd.nextGaussian
-- $ cabal install random
import System.Random

getStdRandom (randomR (0, 99))
getStdRandom (randomR (0.0, 1.0))
none
random seed
set, get, restore
Random.init 17;;
let seed = Random.get_state();;
Random.set_state seed;;
let rnd = System.Random(17)
none
none
import scala.util.Random

val rnd = Random

rnd.setSeed(17)
none
none
-- $ cabal install random
import System.Random

setStdGen $ mkStdGen 17
seed <- getStdGen
setStdGen seed
bit operators 1 lsl 4
1 lsr 4
1 land 3
1 lor 3
1 lxor 3
lnot 1
1 <<< 4
1 >>> 4
1 &&& 3
1 ||| 3
1 ^^^ 3
~~~ 1
1 << 4
1 >> 4
1 & 3
1 | 3
1 ^ 3
~ 1
import Data.Bits

x = 1 :: Integer
y = 3 :: Integer

shiftL x 4
shiftR x 4
x .&. y
x .|. y
xor x y
complement x
binary, octal, and hex literals 0b101010
0o52
0x2a
0b101010
0o52
0x2a
none
052
0x2a
none
052
0x2a
radix Integer.toString(42, 7)
Integer.parseInt("60", 7)
strings
ocaml f# scala haskell
string type
 
string string java.lang.String String
string literal
 
"Hello, World!" "Hello, World!" "Hello, World!"

"""Hello, World!"""
"Hello, World!"
newline in literal no yes in triple quote literal only no
literal escapes \b \n \r \t \" \' \\
\ooo \xhh
\b \n \r\ t \" \' \\
\uhhhh \Uhhhhhhhh
\b \f \n \r \t \" \'
\uhhhh \o \oo \ooo
\a \b \f \n \r \t \v \" \& \' \\
\oo... \d... \xh...

Octal, decimal, and hex escapes denote Unicode characters and can contain anywhere from 1 to 7 digits. The max values are \o4177777, \1114111, and \x10ffff. The \& escape does not represent a character, but can separate a numeric backslash escape sequence from a following digit.
format string sprintf "foo %s %d %.2f" "bar" 7 3.1415 "foo %s %d %.2f".format("bar", 7, 3.1415) import Text.Printf

printf "foo %s %d %.2f" "bar" 7 3.1415
concatenate
 
"Hello" ^ ", " ^ "World!" "Hello" + ", " + "World!" "Hello" + ", " + "World!" "Hello" ++ ", " ++ "World!"
replicate
 
String.make 80 '-' String.replicate 80 "-" val hbar = "-" * 80 concat ( replicate 80 "-" )
translate case
to upper, to lower
String.uppercase "hello"
String.lowercase "HELLO"
"hello".ToUpper()
"HELLO".ToLower()
"hello".toUpperCase
"HELLO".toLowerCase
import Data.Char

map toUpper "hello"
map toLower "HELLO"
capitalize
 
String.capitalize "hello" "hello".capitalize
trim
both sides, left, right
String.trim " hello " " hello ".Trim()
" hello".TrimStart()
"hello ".TrimEnd()
" hello ".trim
pad
on left, on right
"hello".PadLeft(10, ' ')
"hello".PadRight(10, ' ')
??
"hello".padTo(10, " ").mkString
number to string "two: " ^ string_of_int 2
"pi: " ^ float_of_string 3.14
"two: " + string 2
"pi: " + string 3.14
"two: " + 2.toString
"pi: " + 3.14.toString
"two: " ++ (show 2)
"pi: " ++ (show 3.14)
string to number 7 + int_of_string "12"
73.9 +. float_of_string ".037"
7 + int "12"
73.9 + float ".037
7 + "12".toInt
73.9 + ".037".toFloat
raises NumberFormatException if string doesn't completely parse
7 + (read "12")::Integer
73.9 + (read "0.037")::Double
raises exception if string doesn't completely parse
join
 
System.String.Join(" ", ["do"; "re"; "mi"]) List("do", "re", "mi").mkString(" ")
split
 
"do re mi".Split(' ') "do re mi".split(" ")
character type
 
char char Char Char
character literal 'h' 'h' 'h' 'h'
length
 
String.length "hello" "hello".Length "hello".length length "hello"
index of substring "hello".IndexOf("hell") "hello".indexOf("hell")
extract substring String.sub "hello" 0 4 "hello".Substring(0, 4) "hello".substring(0, 4) drop 0 (take 4 "hello")
extract character "hello".[0] "hello".[0] "hello"(0) "hello" !! 0
chr and ord Char.code 'a'
Char.chr 97
int 'a'
char 97
'a'.toInt
97.toChar
Char.ord 'a'
Char.chr 97
dates and time
ocaml f# scala haskell
date and time types ClockTime CalendarTime TimeDiff
current date and time import Time

t <- getClockTime
current unix epoch open Unix;;

(* float: *)
time();;
import System.Time

getClockTime >>= (\(TOD sec _) -> return sec)
arrays
ocaml f# scala haskell
literal val a = Array(1, 2, 3)
size a.size
lookup val n = a(0)
update a(2) = 4
out-of-bounds raises java.lang.ArrayIndexOutOfBounds
lists
ocaml f# scala haskell
literal [1; 2; 3] [1; 2; 3] // none; use constructor:
List(1, 2, 3)
[1, 2, 3]
empty list
 
[] Nil
List()
[]
empty list test let list = [1; 2; 3];;

list == []
val list = List(1, 2, 3)

list == Nil
list.isEmpty
let list = [1, 2, 3]

list == []
null list
cons
 
1 :: [2; 3] 1 :: [2; 3] 1 :: List(2, 3) 1 : [2, 3]
head
 
List.hd [1; 2; 3] List.head [1; 2; 3] List(1, 2, 3).head head [1, 2, 3]
tail
 
List.tl [1; 2; 3] List.tail [1; 2; 3] List(1, 2, 3).tail tail [1, 2, 3]
head and tail of empty list exceptions // NoSuchElementException:
Nil.head

// UnsupportedOperationException:
Nil.tail
exceptions
length
 
List.length [1; 2; 3] List.length [1; 2; 3] List(1, 2, 3).length length [1, 2, 3]
nth element
 
List.nth [1; 2; 3] 0 List.nth [1; 2; 3] 0 List(1, 2, 3)(0) [1, 2, 3] !! 0
element index // evaluates to 1:
List(7, 8, 9).indexOf(8)

// evaluates to -1:
List(7, 8, 9).indexOf(10)
import Data.list

-- Just 1:
elemIndex 8 [7, 8, 9]

-- Nothing:
elemIndex 10 [7, 8, 9]
update // evaluates to List(1, 4, 3):
List(1, 2, 3).updated(1, 4)
concatenate
two lists, list of lists
[1; 2] @ [3; 4]
List.append [1; 2] [3; 4]

List.concat [[1; 2]; [3; 4]]
[1; 2] @ [3; 4]
List.append [1; 2] [3; 4]

List.concat [[1; 2]; [3; 4]]
List(1, 2) ::: List(3, 4)
List(1, 2) ++ List(3, 4)

List(List(1, 2), List(3, 4)).flatten
[1, 2] ++ [3, 4]

concat [[1, 2], [3, 4]]
last
and butlast
List(1, 2, 3).last
List(1, 2, 3).init
last [1, 2, 3]
init [1, 2, 3]
take
 
List(1, 2, 3).take(2) take 2 [1, 2, 3]
drop
 
List(1, 2, 3).drop(2) drop 2 [1, 2, 3]
iterate let f i =
  print_endline (string_of_int i);;

List.iter f [1; 2; 3];;
let f i =
  System.Console.WriteLine(string i)

List.iter f [1; 2; 3]
List(1, 2, 3).foreach(i => println(i)) mapM_ print [1, 2, 3]
reverse
 
List.rev [1; 2; 3] List.rev [1; 2; 3] List(1, 2, 3).reverse reverse [1, 2, 3]
sort List.sort min [1; 3; 2; 4]
List.sort max [1; 3; 2; 4]
List.sort [1; 3; 2; 4] List(1, 3, 2, 4).sortWith((x, y) => x < y)
List(1, 3, 2, 4).sortWith(_ < _)
List(1, 3, 2, 4).sortWith((x, y) => x > y)
List(1, 3, 2, 4).sortWith(_ > _)
import Data.List

sort [1, 3, 2, 4]
map List.map (( * ) 2) [1; 2; 3] List.map (( * ) 2) [1; 2; 3] List(1, 2, 3).map(x => 2 * x)
List(1, 2, 3).map(2 * _)
map (\x -> x * x) [1, 2, 3]
filter
 
List.filter ((<) 2) [1; 2; 3] List.filter ((<) 2) [1; 2; 3] List(1, 2, 3).filter(x => x > 2) filter (\x -> x > 2) [1, 2, 3]
fold from left List.fold_left (+) 0 [1; 2; 3] List.fold (-) 0 [1; 2; 3] List(1, 2, 3).foldLeft(0)(_ + _)
List(1, 2, 3).foldLeft(0)((x, y) => x + y)
foldl (+) 0 [1, 2, 3]
fold from right
 
List.fold_right (-) [1; 2; 3] 0 List(1, 2, 3).foldRight(0)(_ - _) foldr (-) 0 [1, 2, 3]
membership
 
List(1, 2, 3).contains(3) elem 3 [1, 2, 3]
universal test
 
List.for_all (fun x -> x > 2) [1; 2; 3];; List.forall (fun x -> x > 2) [1; 2; 3] List(1, 2, 3).forall(_ > 2) all (\x -> x > 2) [1, 2, 3]
existential test
 
List.exists (fun x -> x > 2) [1; 2; 3];; List.exists (fun x -> x > 2) [1; 2; 3] List(1, 2, 3).exists(_ > 2) any (\x -> x > 2) [1, 2, 3]
zip lists -- list of tuples:
zip [1, 2, 3] ['a', 'b', 'c']
tuples
ocaml f# scala haskell
tuple (1, "hello", true) (1, "hello", true) (1, "hello", true) (1, "hello", True)
tuple element access match (1, "hello", true) with _, x, _ -> x match (1, "hello", true) with _, x, _ -> x (1, "hello", true)._1 (\(a, _, _) -> a) (1, "hello", True)
pair element access fst (12, "December")
snd (12, "December")
fst (12, "December")
snd (12, "December")
(12, "December")._1
(12, "December")._2
fst (12, "December")
snd (12, "December")
dictionaries
ocaml f# scala haskell
functions
ocaml f# scala haskell
define function let average a b = ( a +. b ) /. 2.0;; let average a b = ( a + b ) / 2.0 // argument types must be declared:
def average(a: Double, b: Double)
  = (a + b) / 2.0

// return value type must be declared if
// function is recursive:

def factorial(n: Int): Int =
  if (n < 1)
    1
  else
    n * factorial(n - 1)
average a b = (a + b) / 2.0
invoke function (* 4.5: *)
average 1.0 2.0 +. 3.0;;

(* 3.0: *)
average 1.0 (2.0 +. 3.0);;
// 4.5:
average 1.0 2.0 + 3.0

// 3.0:
average 1.0 (2.0 + 3.0)
// 3.0:
average(1, 2 + 3)

// 4.5:
average(1, 2) + 3

// parens can be omitted when a function
// takes no arguments; by convention parens
// are omitted when the function has no
// side effects
-- 4.5:
average 1 2 + 3

-- 3.0:
average 1 (2 + 3)
average 1 $ 2 + 3
define function with block body // braces must be used if body
// not an expression:

def print_numbers() = {
  println("one")
  println("two")
}
named parameter let subtract ~m ~s = m - s;;

subtract ~s: 3 ~m: 7;;
def subtract(m: Int, s: Int) = m - s

subtract(s = 3, m = 7)
none
named parameter default value let logarithm ?(base = (exp 1.0)) x = log x /. (log base);;

logarithm 2.718;;
logarithm ~base: 2.0 10.0;;
def logarithm(x: Double,
              base: Double = math.exp(1)) =
  math.log(x) / math.log(base)

logarithm(2.718)
logarithm(10, base = 2)
none
piecewise defined function let to_s = function Red -> "red"
  | Green -> "green"
  | Blue -> "blue";;
none to_s Red = "red"
to_s Green = "green"
to_s Blue = "blue"
recursive function let rec range a b =
if a > b then []
else a :: range (a+1) b;;
def range(a:Int, b:Int): List[Int] =
  if (a > b)
    List()
  else
    a :: range(a + 1, b)
range a b = if a > b then [] else a : range (a+1) b
mutually-recursive-functions let rec even n = if n = 0 then true else odd (n-1)
and odd n = if n = 0 then false else even (n-1);;
anonymous function fun x -> fun y -> (x +. y) /. 2.0 fun x -> fun y -> (x + y) / 2.0 (x: Double, y: Double) => (x + y) / 2.0 \x y -> (x+y) / 2.0
infix operator in prefix position ( * ) 3 4;; none ( * ) 3 4
function in infix position none unary methods can be used as binary operators add x y = x + y
3 ‘add` 4
currying let plus2 = (+) 2;; def plus(x: Int)(y: Int) = x + y
plus(3)(7)
def plus2 = plus(2)
plus2(7)
plus2 = (+) 2
composition f x = x + 2
g x = x * 3
(f . g ) 4
function composition operator none none double x = 2 * x
quadruple x = double . double
lazy evaluation let arg1 x y = x;;

arg1 7 (lazy (1/0) );;
def arg1(x: => Int, y: => Int): Int = x

arg1(7, 1 / 0)
lazy evaluation is default:
arg1 x y = x

arg1 7 (error "bam!")
strict evaluation default behavior default behavior default behavior arg1 x y = seq y x

arg1 7 (error "bam!")
execution control
ocaml f# scala haskell
if if x > 0 then
  print_endline "pos";;
if x > 0 then
  printfn "pos"
if ( x > 0 )
  println("pos")
if x > 0
  then putStrLn "pos"
  else return ()
if else-if else if x > 0 then
  print_endline "pos"
else
  if x < 0 then
    print_endline "neg"
  else
    print_endline "zero";;
if x > 0 then
  printfn "pos"
else
  if x < 0 then
    printfn "neg"
  else
    printfn "zero"
if (x > 0)
  println("pos")
else if (x < 0)
  println("neg")
else
  println("zero")
if x > 0
  then putStrLn "pos"
  else if x < 0
    then putStrLn "neg"
    else putStrLn "zero"
sequencing print_endline "one";
print_endline "two";
print_endline "three";;
printfn "one"
printfn "two"
printfn "three"
println("one")
println("two")
println("three")
do
  putStrLn "one"
  putStrLn "two"
  putStrLn "three"
while let i = ref 0;;

while !i < 10 do
  print_endline (string_of_int !i);
  i := !i + 1
done;;
let i = ref 0

while !i < 10 do
  printfn "%d" !i
  i := !i + 1
var i = 0
while (i<10) {
  printf("%d\n", i)
  i = i+1
}
for for i = 1 to 10 do
  let s = string_of_int i in
  print_endline s
done;;
for (i <- 1 to 10)
  println(i)
for in reverse for i = 10 downto 1 do
  let s = string_of_int i in
  print_endline s
done;;
none
list iteration none for (i <- List.range(1, 11).reverse)
  println(i)
loop let rec loop i =
  if i <= 10 then begin
    print_endline (string_of_int i);
    loop (i+1)
  end in
loop 0;;
none
exceptions
ocaml f# scala haskell
raise error raise (Failure "bam!");;
or
failwith "bam!";;
throw new Exception("bam!") error "bam!"
handle error let x = try 1 / 0 with Division_by_zero -> 0;; import java.lang._
 
val x = try {
  1 / 0
}
catch {
  case e: ArithmeticException => 0
}
type of exceptions exn
user defined exception exception Foo of string;;
raise (Foo "invalid input");;
standard exceptions Division_by_zero
Failure string
Not_found
Invalid_argument string
Match_failure (string, int, int)
Assert_failure (string, int, int)
Out_of_memory
Stack_overflow
assert assert(1 = 0);; assert(1 == 0)
concurrency
ocaml f# scala haskell
file handles
ocaml f# scala haskell
standard file handles stdin stdout stderr stdin stdout stderr System.in System.out System.err import System.Posix.IO

stdInput stdOutput stdError
read line from stdin let line = read_line();; val line = readLine() line <- getLine
end-of-file behavior raises End_of_file when last data is returned, hIsEOF will return True. Reading after end-of-file throws an exception.
chomp
write line to stdout print_endline "lorem ipsum";; printfn "lorem ipsum" println("lorem ipsum") putStrLn "lorem ipsum"
write formatted string to stdout
open file for reading let f = open_in "/etc/passwd";; import scala.io.Source

val path = "/etc/hosts"
val f = Source.fromFile(path)
import System.IO

f <- openFile "/etc/hosts" ReadMode
open file for writing let f = open_out "/tmp/ocaml.out";; import System.IO

f <- openFile "/tmp/test" WriteMode
open file for appending import System.IO

f <- openFile "/tmp/err.log" AppendMode
close file import scala.io.Source

f.close
import System.IO

hClose f
i/o errors
read line let ic = open_in "/etc/passwd" in
let line = input_line ic in
print_endline line;;
import scala.io.Source
val src = Source.fromFile("/etc/passwd")
for (line <- src.getLines)
  print(line)
import IO

readAndPrintLines h = do
  eof <- hIsEOF h
  if eof
    then return ()
    else do
      line <- hGetLine h
      putStrLn line
      readAndPrintLines h

main = do
  h <- openFile "/etc/passwd" ReadMode
  readAndPrintLines h
iterate over file by line
read file into array of strings
read file into string
write string
write line open Printf
let oc = open_out "/tmp/test-ocaml" in
fprintf oc "hello out\n";
close_out oc;;
val out = new java.io.FileWriter("/tmp/test-scala")
out.write("hello out\n")
out.close
s = "hello out\n"
f = "/tmp/test-haskell"
main = writeFile f s
flush file handle
end-of-file test
get and set filehandle position
files
ocaml f# scala haskell
file test, regular file test open Unix

try Some (stat "/etc/hosts") with
  Unix_error (ENOENT, _, _) -> None

(stat "/etc/hosts").st_kind = S_REG
import System

Directory.doesFileExist "/etc/hosts"

import Control.Monad
import System.Posix.Files

liftM isRegularFile (getFileStatus "/etc/hosts")
file size (stat "/etc/hosts").st_size import Control.Monad
import System.Posix.Files

liftM fileSize (getFileStatus "/etc/hosts")
is file readable, writable, executable open Unix

try access "/tmp/bar" [R_OK]; true with
  Unix.Unix_error (EACCES, _, _) -> false;;
try access "/tmp/bar" [W_OK]; true with
  Unix.Unix_error (EACCES, _, _) -> false;;
try access "/tmp/bar" [X_OK]; true with
  Unix.Unix_error (EACCES, _, _) -> false;;
import Control.Monad

liftM readable
  (getPermissions "/etc/hosts")
liftM writable
  (getPermissions "/etc/hosts")
liftM executable
  (getPermissions "/etc/hosts")
set file permissions open Unix

chmod "/tmp/foo" 0o755
import System.Posix.Files

setFileMode "/tmp/foo" ownerModes
setFileMode "/tmp/foo" groupReadMode
setFileMode "/tmp/foo" groupExecuteMode
setFileMode "/tmp/foo" otherReadMode
setFileMode "/tmp/foo" otherExecuteMode
copy file, remove file, rename file open Unix

??
unlink "/tmp/foo"
rename "/tmp/bar" "/tmp/foo"
import System.Directory

copyFile "/tmp/foo" "/tmp/bar"
removeFile "/tmp/foo"
renameFile "/tmp/bar" "/tmp/foo"
create symlink, symlink test, readlink open Unix

symlink "/etc/hosts" "/tmp/hosts"
(lstat "/tmp/hosts").st_kind = S_LNK
readlink "/tmp/hosts"
import System.Posix.Files

createSymbolicLink "/etc/hosts" "/tmp/hosts"
??
readSymbolicLink "/tmp/hosts"
generate unused file name open Filename

(* prefix and suffix: *)
temp_file "foo" ".txt"
directories
ocaml f# scala haskell
build pathname open Filename

concat "/etc" "hosts"
import System.FilePath ((</>))

let path = "/etc" </> "hosts"
dirname and basename open Filename

dirname "/etc/hosts"
basename "/etc/hosts"
import System.FilePath

takeFileName "/etc/hosts"
takeDirectory "/etc/hosts"
iterate over directory by file import System

-- returns IO [FilePath]
Directory.getDirectoryContents "/etc"
make directory (* opam install fileutils *)
open FileUtil

mkdir ~parent:true "/tmp/foo/bar"
import System.Directory

createDirectoryIfMissing True
  "/tmp/foo/bar"
remove empty directory open Unix

rmdir "/tmp/foodir"
import System.Directory

removeDirectory "/tmp/foodir"
remove directory and contents import System.Directory

removeDirectoryRecursive "/tmp/foodir"
directory test import System

Directory.doesDirectoryExist "/tmp"
temporary directory
processes and environment
ocaml f# scala haskell
command line arguments for i = 0 to Array.length Sys.argv - 1 do
  print_endline i Sys.argv.(i)
done
object Test {
  def main(args: Array[String]) {
    for (arg <- args)
      println(arg)
  }
}
import System

printArgs args = do
  if length args == 0
    then return ()
    else do
      putStrLn (head args)
      printArgs (tail args)
main = do
  a <- getArgs
  printArgs a
program name
 
import System

s <- getProgName
getopt
get and set environment variable
 
open Unix

s = getenv "HOME"
putenv "PATH" "/bin"
import System.Posix.Env

s <- getEnv "HOME"
putEnv "PATH=/bin"
get pid, parent pid open Unix

let pid = getpid()
let ppid = getppid()
import System.Posix.Process

pid <- getProcessID
ppid <- getParentProcessID
get user id and name let uid = getuid()
let username =
  (getpwuid (getuid())).pw_name
import System.Posix.User

uid <- getRealUserID
username <- getLoginName
exit
 
exit 0

exit 1
import System.Exit

exitWith ExitSuccess

to return nonzero status:
exitWith (ExitFailure 1)
set signal handler
 
external command
 
import System.Cmd

rawSystem "ls" ["-l", "/tmp"]
escaped external command
 
backticks
 
libraries and namespaces
ocaml f# scala haskell
namespace example Baz.scala
package Foo.Bar;

class Baz {
  def say() { println("hello"); }
}

Main.scala
import Foo.Bar.Baz;

object Main {
  def main(args : Array[String]) {
    val baz = new Baz;
    baz.say();
  }
}

to compile and run
$ scalac Baz.scala
$ scalac Main.scala
$ scala Main
hello
Foo/Bar.hs
module Foo.Bar where
  data Baz = Baz
  say Baz = putStrLn "hello"

Main.hs
module Main where
import Foo.Bar
baz = Baz
main = say baz

to compile and run
$ ghc -c Foo/Bar.hs
$ ghc Main.hs
$ ./Main
hello
namespaces values, constructors, type variables, type constructors, type classes, modules
file name restrictions module Foo.Bar must be in Foo.ml none module Foo.Bar must be in Foo/Bar.hs
namespace open Graphics;; import Data.Bytestring
namespace creation put code in file MODULE_NAME.ml
namespace alias module Gr = Graphics;; import qualified Data.Bytestring as B
namespace separator . .
subnamespace in A.ml:
module B =
sig
  val display_instruction : unit -> unit
end =
struct
  let msg = "attack"
  let display_instruction () = print_endline msg
end
in client source:
A.B.display_instruction;;
package manager setup do this once:
$ opam init

for each shell session:
$ eval $(opam config env)
package manager
search; install; list installed
$ opam search utop
$ opam install utop
$ opam list --installed
$ cabal list parsec
$ cabal install parsec
$ cabal list --installed
compile app using package
user-defined types
ocaml f# scala haskell
type synonym
 
type name = string;; type name = string type Name = String type Name = String
sum type type color = Red | Green | Blue;;

let col = Red;;

(* evaluates to true: *)
col < Green;;
type color = Red | Green | Blue

let col = Red

// evaluates to true:
col < Green
abstract class Color

case object Red extends Color
case object Blue extends Color
case object Green extends Color

val col = Red

// this won’t compile:
col < Green
data Color = Red | Green | Blue

col = Red

-- this won't compile:
col < Green
tuple product type with one field type special_int = SpecialInt of int;;

let n = SpecialInt 7;;
type special_int = SpecialInt of int

let n = SpecialInt 7
class SpecialInt(x: Int)

val n = new SpecialInt(7)
data SpecialIntType = SpecialInt Integer

n = SpecialInt 7
tuple product type with two fields type int_pair = IntPair of int * int;;

let p = IntPair (7, 11);;
type int_pair = IntPair of int * int

let p = IntPair (7, 11)
class IntPair(a: Int, b: Int)

val p = new IntPair(7, 11)
data IntPairType = IntPair Integer Integer

p = IntPair 7 11
record product type type customer = {
  id: int;
  name: string;
  address: string
};;
type customer = {
  id: int;
  name: string;
  address: string
}
case class Customer(
  id: Int,
  name: String,
  address: String
)
data CustomerType = Customer {
  customerId :: Integer,
  name :: String,
  address :: String
}
record product type literal let cust = {
  id=7;
  name="John";
  address="Topeka, KS"
};;
{id=7; name="John"; address="Topeka, KS"} Customer(7,"John","Topeka, KS")

Customer(id=7, name="John", address="Topeka, KS")
Customer {
  customerId=7,
  name="John",
  address="Topeka, KS" }
generic type type ('a, 'b) twosome =
  Twosome of 'a * 'b;;

let p = Twosome ("pi", 3.14);;
type ('a, 'b) twosome =
  Twosome of 'a * 'b

let p = Twosome ("pi", 3.14)
class Twosome[A, B](a: A, b: B)

val p = new Twosome("pi", 3.14)
data TwosomeType a b = Twosome a b

p = Twosome ("pi", 3.14)
recursive type type binary_tree =
  | Leaf of int
  | Tree of binary_tree * binary_tree;;
type binary_tree =
  | Leaf of int
  | Tree of binary_tree * binary_tree
abstract class BinaryTree
case class Tree(left: BinaryTree, right: BinaryTree) extends BinaryTree
case class Leaf(x: Int) extends BinaryTree
data BinaryTree = Leaf Integer | Tree BinaryTree BinaryTree
pattern match sum type let col = Red;;

let s = match col with
  | Red -> "red"
  | Blue -> "blue"
  | Green -> "green";;
val c:Color = Red;
c match { case Red => "red"; case Green => "green"; case Blue => "blue" }
c = Red
case c of Red -> "red"
  Green -> "green"
  Blue -> "blue"
pattern match product type
pattern match guard match i with j when i < 0 -> -j | j -> j;; match { case i: Int if i < 0 => - i; case i: Int => i } none, use if or piecewise function definition
pattern match catchall let to_s c = match c with Red -> "red" | _ -> "not red";;
to_s Green;;
val c : Color = Green
c match { case Red => "red"; case _ => "not red" }
c = Green
case c of Red -> "red"; _ -> "not red"
objects
ocaml f# scala haskell
class definition class counter = object
  val mutable n = 0
  method incr = n <- n+1
  method get = n
end;;
class Counter {
  private var n = 0
  def incr(): Unit = { n = n+1 }
  def get(): Int = { n }
}
object creation let c = new counter;; val c = new Counter
method invocation c#incr;;
c#get;;
c.incr
c.get
field access none
polymorphism
ocaml f# scala haskell
overload function
inheritance
net and web
ocaml f# scala haskell
unit test
ocaml f# scala haskell
debugging and profiling
ocaml f# scala haskell
repl
ocaml f# scala haskell
invoke repl $ ocaml

Use this if you want history:
$ rlwrap ocaml

The utop toplevel, which can be installed via opam, also provides history.
Mono:
$ fsharpi

In visual studio, highlight code and press ALT+ENTER.
$ scala $ ghci
repl limitations Must use let to define values and functions; when defining functions with multiple equations the equations must be separated by semicolons; the clauses of case/of statements must be separated by semicolons; it is not possible to define data types.
repl last value none it res0, res1, … it
help none :help :?
quit ^D #quit;;
inspect type repl displays the type of any expression entered repl displays the type of any expression entered let a = 3
:type a
inspect namespace module Unix = Unix;;
load source file #use "hello";; :edit hello.hs
:load hello
load package consider adding to .ocamlinit:
#use "topfind";;
# thread;;
#require "core";;
open Core.Std;;
search path #directory "libdir";;
set search path on command line ocaml -Ilibdir
_______________________________________________ _______________________________________________ _______________________________________________ _______________________________________________

version used

Versions used to test the code samples in this sheet.

show version

How to get the version.

Grammar and Invocation

interpreter

How to run the interpreter on a file of source code.

scala:

Scala can be run "Perl style" like this:

scala foo.scala

or "Java style" like this:

scala Foo

When the code is run "Java style", the code to be executed must be in the main method of an object with the same name as the file. When the code is run "Perl style" the statements o be executed should be at the top level outside of any object, class, or method.

shebang

How to use the interpreter in a shebang.

scala

To use scala as a shebang, it is necessary to terminate the shell script portion of the script with !#

#!/bin/sh
exec scala $0 $@
!#
println("hello world")

bytecode compiler and interpreter

How to compile source to bytecode and run it.

ocaml:

It is not necessary to invoke ocamlrun on the bytecode; the bytecode can be executed directly because the bytecode compiler puts a shebang invocation at the top of the file.

native compiler

How to compile source to native code and run it.

library which is always imported

The name of the library containing the types and functions which are always available.

statement terminator

ocaml:

;; is the ocaml statement separator. It is not necessary at the end of the line if the following line starts with an open or let keyword or at the end of the file.

scala:

Scala infers the existence of a semicolon at the end of a newline terminated line if none of the following conditions hold:

  • the line ends with a infix operator, including a period
  • the following line begins with a word that is not legal at the start of a statement
  • the line ends inside parens or square brackets, neither of which can contain multiple statements

blocks

How to define a block of statements.

end-of-line comment

A comment terminated by the end of the line.

multiple line comment

A comment with a start and end delimiter which can span multiple lines.

ocaml:

(* *) style comments can be nested.

Variables and Expressions

write-once variable

How to define a variable which can be set at run-time but cannot be modified after it is set.

modifiable variable

How to define a modifiable variable.

unit type and value

The notation for the unit type and the unit value. In all languages the notation for the unit value is the same as the notation for an empty tuple.

The unit value is a common return value of functions which perform side effects.

conditional expression

The syntax for a conditional expression.

branch type mismatch

What happens if the two branches of a conditional expression don't have the same type.

null

A value used somewhat paradoxically to indicate the absence of a value.

Types which can contain a null value are called option types.

nullable type

null test

coalesce

expression type declaration

How to explicitly declare the type of an expression.

let ... in ...

How to define local variables.

ocaml:

OCaml uses let to define a value and let with in to define values in a local scope. OCaml follows the usage of the original dialect of ML in this respect.

OCaml can define multiple values with a single let and in by conjoining the definitions with and. The definitions are performed in parallel, so later definitions cannot use the earlier definitions:

let z = 
let x = 3
and y = 4 in
x * y;;

scala:

Blocks can be used in Scala exclusively to define scope. Furthermore blocks are expressions and evaluate to their last statement.

haskell:

Haskell uses let with in to define local scope. In addition, ghci uses let without in to define values.

where

How to define local variables with definitions after the expression that uses them.

Arithmetic and Logic

boolean type

The type for boolean values.

true and false

The literals for true and false.

logical operators

The logical operators: and, or, and not.

relational operators

Operators for performing comparisons.

min and max

The binary functions min and max.

integer types

The most commonly used numeric types.

scala:

Arithmetic operators can be used on values of type Char, which then behaves as a 16 bit unsigned integer. Integer literals are of type Int unless suffixed with L:

scala> 9223372036854775807L
res24: Long = 9223372036854775807

scala> 9223372036854775807 
<console>:1: error: integer number too large

integer literal

Integer literals.

haskell:

Haskell does not have negative integer literal syntax. The negative sign parses as a unary prefix operator. It may be necessary to put parens around a negative integer constant:

-- syntax error:
1 + -3

-- ok:
1 + (-3)

float type

Floating point types.

integer operators

The integer operators.

float operators

The floating point operators. Note that in the OCaml the floating point operators are different from the integer operators.

add integer and float

How to add an integer and a float.

ocaml:

OCaml also can convert a integer to float with float_of_int.

integer division

How to find the quotient of two integers; how to find the remainder of two integers.

integer division by zero

The result of dividing an integer by zero.

float division

float division by zero

The result of division by zero.

float exponentiation

How to exponentiate a float.

float functions

The square root function; the natural exponential and natural logarithm functions; the trigonometric functions.

arithmetic truncation

Ways to convert a float to a nearby integer.

ocaml:

This definition of round handles negative numbers correctly:

let round x = int_of_float (floor (x +. 0.5))

power

How to perform exponentiation.

ocaml:

How to define a function which computes the power of an integer:

let integer_exponent b e =
  let rec aux x i =
    if i = e then x else aux (x * b) (i + 1)
  in
  aux 1 0;;

sqrt -1

The result of taking the square root of a negative number.

transcendental functions

transcendental constants

integer overflow

What happens when expression evaluates to an integer that is larger than what can be stored.

scala:

The largest integers are available in the constants Int.MaxValue and Long.MaxValue.

float overflow

The result of float overflow.

Ocaml has literals for infinity and negative infinity, but Scala and Haskell do not.

rational type

rational construction

rational decomposition

complex type

complex construction

complex decomposition

random number

How to generate a uniformly distributed random integer; how to generate a uniformly distributed float; how to generate a normally distributed float.

scala:

One can also use java.util.Random, which does not have to be imported.

random seed

How to set a random seed. How to get and restore the state of a random number generator.

scala:

It looks like Scala 2.10 has modified the Random constructor so that it will accept an Int or Long as a seed argument.

bit operators

The bit operators.

ocaml:

Also has operators which perform arithmetic shift: asl and asr. When performing an arithmetic shift, the sign of the integer is preserved.

haskell:

Haskell does not assign a default size or type to numeric literals. Hence numeric literals must have their type declared for bit operations to be performed on them.

binary, octal, and hex literals

radix

Strings

string type

The types for strings and characters.

string literal

The syntax for a string literal.

newline in literal

literal escapes

scala:

Unicode escapes might not work when scala is installed on a Mac because the encoding is set by default to MacRoman:

scala> System.getProperty("file.encoding")
res0: java.lang.String = MacRoman

This can be fixed by passing the following flag to java in the scala shell script:

-Dfile.encoding=UTF-8

format string

concatenate

How to concatenate strings.

f#:

F# supports (with a warning) the ^ operator for compatibility with OCaml.

replicate

translate case

How to convert a string to uppercase; how to convert a string to lowercase; how to capitalize the first character.

capitalize

trim

pad

number to string

string to number

How to parse numeric types from string; how to convert numeric types to strings.

ocaml:

To convert a string to a float:

float_of_string "3.14"

scala:

The + operator will convert a numeric type to a string if the other operand is a string. Hence the following works:

"value: " + 8

join

split

character type

character literal

length

How to get the length of a string.

index of substring

How to get the index of a substring.

extract substring

How to extract a substring.

extract character

How to get the character at a specified index of a string.

The syntax for a character literal.

chr and ord

How to convert a character to its ASCII code or Unicode point; how to convert an ASCII code or Unicode point to a character.

Dates and Time

Arrays

Lists

list literal

list element element

list head

f#:

Supports List.hd (with a warning) to be compatible with OCaml.

list-tail

Supports List.tl (with a warning) to be compatible with OCaml.

Tuples

tuple

tuple element

Functions

function

How to define a function.

scala

Recursive functions must have their return type declared because the Scala compiler cannot infer it.

lambda

How to define an anonymous function.

piecewise defined function

How to define a function with multiple equations and matching on the arguments.

recursive function

How to define a recursive function.

mutually recursive functions

How to define two functions which call each other. Mutual recursion can be eliminated by inlining the second function inside the first function. The first function is then recursive and can be defined independently of the second function.

named parameter

How to define and invoke a function with named parameters.

ocaml:

Multiple parameters can share a name. In the function definition colons are used to rename the parameters for use in the function body.

let add_xs ~x:x1 ~x:x2 = x1 + x2;;
add_xs ~x:3 ~x:7;;

named parameter default value

How to make named parameters optional by providing a default value in the definition.

ocaml:

For a named parameter to be optional, it must be following by an unnamed parameter in the definition. This permits the parser to unambiguously determine if the optional parameter has been provided or not. If the optional parameter is not followed by an unnamed parameter in the definition, then named parameter is not optional. If the function is invoked without the parameter, it returns a curried version of the function which expects the missing named parameter as an argument.

infix operator in prefix position

How to invoke an infix operator in prefix position.

function in infix position

How to invoke a function in infix position.

currying

How to create a curried function by providing values for some of the arguments of a function.

scala:

Functions can only be curried if they are defined with special syntax. Functions defined with this syntax must be invoked with a pair of parens for each argument.

function composition operator

An operator which takes two functions as arguments and returns a function constructed from them by composition.

lazy evaluation

How to evaluate the arguments to a function in a lazy manner.

Lazy evaluation is also called call-by-name.

ocaml:

OCaml provides the lazy function. It is up to the caller to specify that the argument is to evaluated lazily.

scala:

Functions can be defined to evaluate their arguments lazily by putting a => operator between the colon and the type of the parameter in the function signature.

We can define arg1 so that the first argument is strict and the second argument is lazy:

def arg1(x: Int, y: => Int): Int = x

arg1(7, 1 / 0)

haskell:

Haskell evaluates arguments lazily by default.

strict evaluation

How to evaluate arguments before they are passed to a function.

Strict evaluation is also called call by-value.

haskell:

The seq function evaluates its first argument and then returns the second argument.

Execution Control

if

if else-if else

sequencing

while

ocaml:

There is no break or continue statement. In addition to using references, it is possible to use exceptions to break out of a while loop.

for

How to loop over a range of integers.

sml:

How to define a for loop in SML:

datatype for = to of int * int
             | downto of int * int

infix to downto

val for =
    fn lo to up =>
       (fn f => let fun loop lo = if lo > up then ()
                                  else (f lo; loop (lo+1))
                in loop lo end)
     | up downto lo =>
       (fn f => let fun loop up = if up < lo then ()
                                  else (f up; loop (up-1))
                in loop up end)

How to use the for loop:

for (1 to 9)
    (fn i => print (Int.toString i))

for (9 downto 1)
    (fn i => print (Int.toString i))

for in reverse

How to iterate over a reversed range of integers.

list iteration

How to iterate over the members of a list.

loop

An infinite loop.

Exceptions

raise error

How to raise an error.

handle error

How to handle an error.

Concurrency

Filehandles

Files

Directories

Processes and Environment

Libraries and Namespaces

namespace example

namespaces

file name restrictions

import

namespace creation

namespace alias

namespace separator

subnamespace

inspect namespace

User-Defined Types

keywords used to define types by language
pascal c c++ ocaml scala haskell
type synonym type typedef typedef type type type
sum type type enum or union type abstract class data
tuple product type type data
record product type record struct struct or class type of class data

Examples of algebraic sum types are the enumerated type of Pascal and the enum of C. The definition of the type lists a set of values which variables which have the type can contain. The values are called variants.

The enumerated type of Pascal and the enum of C are implemented as integers, and one can recover the underlying integer value associated with each variant. In Pascal one uses the ord function to do this. One can use the equality test operator to determine whether two variables hold the same variant. One can also use the less than (<) operator to determine if a variable holds a variant which occurs earlier in the type definition list than another.

An enumerated type is thus similar to defining a sequence of integer constants like this:

  typedef int month;

  const month JANUARY = 1;
  const month FEBRUARY = 2;
  .
  .
  .
  const month DECEMBER = 12;

An enumerated type gives the compiler the ability to ensure that only variants listed in the type definition list are actually stored in variables with the enumerated type however.

BETTER EXPLANATION AND MOTIVATION OF UNARY TYPES. OTHER THAN VARIANTS: UNIT. ARE
UNARY TYPES USEFUL?

Algebraic sum types are more general than enumerated types, because the variants are not restricted to being unary types. By a unary type we mean a type whose variables can only contain a single value. EXAMPLE OF SUCH AND ALGEBRAIC SUM TYPE. Because of this generality, one cannot assume that a general algebraic sum type variant has an integer representation. Some languages nevertheless define an order on the variants.

SUM TYPE: NUMBER OF VALUES IS THE SUM OF THE VALUES OF EACH OF THE VARIANTS

C UNION TYPE AS ALGEBRAIC SUM TYPE

Examples of algebraic product types are the record of Pascal and the struct of C. An algebraic product type wraps several values into a single "super" value. The components of an algebraic product type are called fields, and each has a type which constrains the values which can be stored in it. The type of each field is normally a pre-existing type, but see the note on recursive types below.

To extract a field from a product value, each field must be identified. In the case of the Pascal and the C struct the fields are given names. Product types can also be defined in which the fields are identified by position like a tuple. OCaml and Haskell support both types of product type.

Since OCaml and Haskell have both tuples and tuple product types, it is worthwhile to consider the differences. One could represent represent coordinates on plane with a simple pair tuple with this type:

  (float, float)

However, all 2-tuples in which the components are both floats are the same type. With tuple product types, we could define two distinct types:

  type cartesian = Cartestion of float * float;
  type polar = Polar of float * float;

The compiler will now prevent us from using cartesian coordinates in a place where polar coordinates are expected.

It is also instructive to consider the difference between a type synonym and a product type with a single field. In the former case the two types are interchangeable. Type synonyms are useful as a shorthand for a long type, such as a 10-tuple or a function type. Functions which operate on variables of the original type will also operate on variables with the type synonym. In fact, it should be noted that type synonyms don't create a constructor, so the constructor for the original type must be used.

A product type with a single field creates a new type and provides a constructor for it which accepts the original type as an argument. Functions which take the original type as an argument cannot be used on the new type.

COMBINED ALGEBRAIC TYPES.

Algebraic product types first appeared in 1966 in Algol W. Algol W extended Algol 60 by adding a record type. The idea was due to Niklaus Wirth and C. A. R. Hoare. Pascal, which appeared in 1970, had both a record type and an enumerated type as already noted, and the Pascal enumerated type seems to be the first example of a type that could be called an algebraic sum type.

Algebraic types first appeared in their full generality in the programming language called Hope, circa 1980. Algebraic types were soon borrowed into ML. Hope introduced the terms algebraic data type, product type, and sum type. It also introduced pattern matching.

PATTERN MATCHING.

type synonym

sum type

generic type

recursive type

Objects

Polymorphism

REPL

repl

repl limitations

repl last value

help

ocaml

The OCaml top level provides these directives:

#cd "DIRNAME";;
#directory "DIRNAME";;
#install_printer PRINTER_NAME;;
#label BOOL;;
#load "FILENAME";;
#print_depth N;;
#print_length N;;
#quit;;
#remove_printer PRINTER_NAME;;
#trace FUNCTION_NAME;;
#untrace FUNCTION_NAME;;
#untrace_all;;
#use "FILENAME";;
#warnings "WARNINGS_LIST";;

inspect type

load source file

search path

set search path on command line

OCaml

Install OPAM in 2 minutes (ocamlpro.com)
The Objective-Caml system (inria.fr)
Real World OCaml (oreilly.com)
Standard ML and Objective Caml, Side by Side

F#

Mono (mono-project.com)

Scala

The Scala Language Specification (pdf)
Scala 2.7.7 API
Java 1.6 API

Haskell

Haskell 2010 Language Report
Haskell Hierarchical Libraries
Real World Haskell

content of this page licensed under creative commons attribution-sharealike 3.0