Personal tools

OCaml

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(Syntactic dictionary)
(Syntactic dictionary)
Line 66: Line 66:
 
|
 
|
 
case x of
 
case x of
A x
+
B x
<nowiki>|</nowiki> x > 0 -> ...
+
<nowiki>| x > 0 -> ...
  +
|</nowiki> otherwise -> ...
 
C a b -> ...
 
C a b -> ...
  +
  +
case L () of
  +
L x -> x
  +
R x -> x
 
|
 
|
 
match x with
 
match x with
 
B x when x > 0 -> ...
 
B x when x > 0 -> ...
  +
B x -> ...
 
<nowiki>|</nowiki> C (a, b) -> ...
 
<nowiki>|</nowiki> C (a, b) -> ...
| There doesn't seem to be syntax for multiple guards
+
  +
match L () with
  +
L x <nowiki>|</nowiki> R x -> x
  +
|
 
|}
 
|}
   

Revision as of 13:27, 12 December 2012

OCaml is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.

This page aims to cover some of its differences from Haskell.

1 Syntactic dictionary

Haskell OCaml Comments
Anonymous functions
\x y -> ...
fun x y -> ...
Multiple assignments
let
  x = 4
  y = 5
 in ...
let x = 4
and y = 5
 in ...
Types
Int, Bool, (Double, Char), a
int, bool, float * char, 'a
float is a double type
Type signatures
const :: a -> b -> a
const : 'a -> 'b -> 'a
Signatures usually omitted in OCaml
Type declarations
data A = B Int | C Char Bool
x = B 3
y = C 'a' True
type a = B of int | C of char * bool
let x = B 3
and y = C ('a', true)
Parametrised types
data D a = D (a -> a)
data E a b = L a | R b
type 'a d = D of ('a -> 'a)
type ('a, 'b) e = L of 'a | R of 'b
Pattern matching
case x of
  B x
    | x > 0 -> ...
     | otherwise -> ...
  C a b -> ...
case L () of
  L x -> x
  R x -> x
match x with
    B x when x > 0 -> ...
    B x -> ...
  | C (a, b) -> ...
match L () with
  L x | R x -> x

2 Conceptual differences

OCaml is strict by default, although it has some facility for introducing laziness.

OCaml's let is non-recursive by default, but has the form let rec for defining recursive functions.

OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.