[I2 logo] [RWTH logo] MOVES: Software Modeling and Verification
(Informatik 2)
Computer Science / RWTH / I2 / Staff / Current / Mohnen / CP / Intro
Printer-friendly
Context Patterns
Introductory Example

If you try to describe how to program a function initlast which splits a list into its initial part and its last element you get something like
Take everything up to but not including a one--element list as initial part and the element of the list as last element.
However, using the standard patterns, you cannot express this. Instead, the recursive search must be programmed explicitly:
initlast :: [a] -> (a,[a])
initlast []     = error "Empty list"
initlast [x]    = ([],x)
initlast (x:xs) = let (ys,l)=initlast xs
                  in (x:ys,l)
Ugly, isn't it?!
Context patterns allow a much shorter and more concise program:
initlast :: [a] -> (a,[a])
initlast []      = error "Empty list"
initlast (c [x]) = ((c []), x)
The context pattern (c [x]) has the variable c in the position of a function and contains the context of [x]: Everything of the list but [x].
Applying this initlast to a list [a1,...,an-1,an] results in
c = \l -> a1:...:an-1:l
x = an
Hence, evaluation of the application (c []) on the right hand side yields the initial part [a1,...,an-1].

Context Patterns
Markus Mohnen
Last modified: Tue Sep 2 09:35:54 MET DST 1997
Valid HTML 4.01 Strict! Valid CSS!