HOME

TheInfoList



OR:

This article describes the features in
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
.


Examples


Factorial

A simple example that is often used to demonstrate the syntax of
functional language In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that m ...
s is the
factorial In mathematics, the factorial of a non-negative denoted is the product of all positive integers less than or equal The factorial also equals the product of n with the next smaller factorial: \begin n! &= n \times (n-1) \times (n-2) \t ...
function for non-negative integers, shown in Haskell: factorial :: Integer -> Integer factorial 0 = 1 factorial n = n * factorial (n-1) Or in one line: factorial n = if n > 1 then n * factorial (n-1) else 1 This describes the factorial as a recursive function, with one terminating base case. It is similar to the descriptions of factorials found in mathematics textbooks. Much of Haskell code is similar to standard
mathematical notation Mathematical notation consists of using symbols for representing operations, unspecified numbers, relations and any other mathematical objects, and assembling them into expressions and formulas. Mathematical notation is widely used in mathematic ...
in facility and syntax. The first line of the factorial function describes the ''type'' of this function; while it is optional, it is considered to be good style to include it. It can be read as ''the function factorial'' (factorial) ''has type'' (::) ''from integer to integer'' (Integer -> Integer). That is, it takes an integer as an argument, and returns another integer. The type of a definition is
inferred Inferences are steps in reasoning, moving from premises to logical consequences; etymologically, the word '' infer'' means to "carry forward". Inference is theoretically traditionally divided into deduction and induction, a distinction that i ...
automatically if the programmer didn't supply a type annotation. The second line relies on
pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
, an important feature of Haskell. Note that parameters of a function are not in parentheses but separated by spaces. When the function's argument is 0 (zero) it will return the integer 1 (one). For all other cases the third line is tried. This is the
recursion Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
, and executes the function again until the base case is reached. Using the product function from the Prelude, a number of small functions analogous to C's
standard library In computer programming, a standard library is the library made available across implementations of a programming language. These libraries are conventionally described in programming language specifications; however, contents of a language's as ...
, and using the Haskell syntax for arithmetic sequences, the factorial function can be expressed in Haskell as follows: factorial n = product ..n Here ..n/nowiki> denotes the arithmetic sequence in list form. Using the Prelude function enumFromTo, the expression ..n/nowiki> can be written as enumFromTo 1 n, allowing the factorial function to be expressed as factorial n = product (enumFromTo 1 n) which, using the function composition operator (expressed as a dot in Haskell) to compose the product function with the curried enumeration function can be rewritten in point-free style: factorial = product . enumFromTo 1 In the Hugs interpreter, one often needs to define the function and use it on the same line separated by a where or let..in. For example, to test the above examples and see the output 120: let in factorial 5 or factorial 5 where factorial = product . enumFromTo 1 The GHCi interpreter doesn't have this restriction and function definitions can be entered on one line (with the let syntax without the in part), and referenced later.


More complex examples


Calculator

In the Haskell source immediately below, :: can be read as "has type"; a -> b can be read as "is a function from a to b". (Thus the Haskell calc :: String ->
loat Loat or LOAT may refer to: People * Lily Loat (1880–1958), British anti-vaccination activist * William Leonard Stevenson Loat (1871–1932), British archaeologist, naturalist, and collector Other * Trausdorf Airport (ICAO: LOAT), a former pu ...
/code> can be read as "calc has type of a function from Strings to lists of Floats".) In the second line calc = ... the equals sign can be read as "can be"; thus multiple lines with calc = ... can be read as multiple possible values for calc, depending on the circumstance detailed in each line. A simple
Reverse Polish notation Reverse Polish notation (RPN), also known as reverse Łukasiewicz notation, Polish postfix notation or simply postfix notation, is a mathematical notation in which operators ''follow'' their operands, in contrast to Polish notation (PN), in whi ...
calculator expressed with the
higher-order function In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: * takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
foldl whose argument ''f'' is defined in a ''where'' clause using
pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
and the
type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
''Read'': calc :: String ->
loat Loat or LOAT may refer to: People * Lily Loat (1880–1958), British anti-vaccination activist * William Leonard Stevenson Loat (1871–1932), British archaeologist, naturalist, and collector Other * Trausdorf Airport (ICAO: LOAT), a former pu ...
calc = foldl f [] . words where f (x:y:zs) "+" = (y + x):zs f (x:y:zs) "-" = (y - x):zs f (x:y:zs) "*" = (y * x):zs f (x:y:zs) "/" = (y / x):zs f (x:y:zs) "FLIP" = y:x:zs f xs y = read y : xs
The empty list is the initial state, and ''f''
interpret Interpreting is a translational activity in which one produces a first and final target-language output on the basis of a one-time exposure to an expression in a source language. The most common two modes of interpreting are simultaneous interp ...
s one word at a time, either as a function name, taking two numbers from the head of the list and pushing the result back in, or parsing the word as a
floating-point number In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can be r ...
and prepending it to the list.


Fibonacci sequence

The following definition produces the list of
Fibonacci numbers In mathematics, the Fibonacci numbers, commonly denoted , form a sequence, the Fibonacci sequence, in which each number is the sum of the two preceding ones. The sequence commonly starts from 0 and 1, although some authors start the sequence from ...
in linear time: fibs = 0 : 1 : zipWith (+) fibs (tail fibs) The infinite list is produced by
corecursion In computer science, corecursion is a type of operation that is dual to recursion. Whereas recursion works analytically, starting on data further from a base case and breaking it down into smaller data and repeating until one reaches a base case, ...
— the latter values of the list are computed on demand starting from the initial two items 0 and 1. This kind of a definition relies on
lazy evaluation In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing). The b ...
, an important feature of Haskell programming. For an example of how the evaluation evolves, the following illustrates the values of ''fibs'' and ''tail fibs'' after the computation of six items and shows how ''zipWith (+)'' has produced four items and proceeds to produce the next item: fibs = 0 : 1 : 1 : 2 : 3 : 5 : ...   + + + + + + tail fibs = 1 : 1 : 2 : 3 : 5 : ...   = = = = = = zipWith ... = 1 : 2 : 3 : 5 : ''8'' : ... fibs = 0 : 1 : 1 : 2 : 3 : 5 : ''8'' : ... The same function, written using
Glasgow Haskell Compiler The Glasgow Haskell Compiler (GHC) is an open-source native code compiler for the functional programming language Haskell. It provides a cross-platform environment for the writing and testing of Haskell code and it supports numerous extensions, ...
's
parallel list comprehension A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical ''set-builder notation'' (''set comprehension'') as distinct from the use of ...
syntax (GHC extensions must be enabled using a special command-line flag, here ''-XParallelListComp'', or by starting the source file with ): fibs = 0 : 1 : a <- fibs , b <- tail fibs or with regular
list comprehension A list comprehension is a Syntax of programming languages, syntactic construct available in some programming languages for creating a list based on existing list (computing), lists. It follows the form of the mathematical ''set-builder notation'' ( ...
s: fibs = 0 : 1 : (a,b) <- zip fibs (tail fibs) or directly self-referencing: fibs = 0 : 1 : next fibs where next (a : t@(b:_)) = (a+b) : next t With
state State may refer to: Arts, entertainment, and media Literature * ''State Magazine'', a monthly magazine published by the U.S. Department of State * ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States * ''Our S ...
ful generating function: fibs = next (0,1) where next (a,b) = a : next (b, a+b) or with unfoldr: fibs = unfoldr (\(a,b) -> Just (a, (b, a+b))) (0, 1) or scanl: fibs = 0 : scanl (+) 1 fibs Using data recursion with Haskell's predefined
fixpoint combinator In mathematics and computer science in general, a '' fixed point'' of a function is a value that is mapped to itself by the function. In combinatory logic for computer science, a fixed-point combinator (or fixpoint combinator) is a higher-order fu ...
: fibs = fix (\xs -> 0 : 1 : zipWith (+) xs (tail xs)) -- zipWith version = fix ((0:) . (1:) . (zipWith (+) <*> tail)) -- same as above, pointfree = fix ((0:) . scanl (+) 1) -- scanl version


Factorial

The factorial we saw previously can be written as a sequence of functions: factorial n = foldr ((.) . (*)) id ..n$ 1 -- factorial 5

((1*) .) ( ((2*) .) ( ((3*) .) ( ((4*) .) ( ((5*) .) id )))) 1 --

(1*) . (2*) . (3*) . (4*) . (5*) . id $ 1 --

1* ( 2* ( 3* ( 4* ( 5* ( id 1 ))))) factorial n = foldr ((.) . (*)) (const 1) ..n$ () -- factorial 5

((1*) .) ( ((2*) .) ( ((3*) .) ( ((4*) .) ( ((5*) .) (const 1) )))) () --

(1*) . (2*) . (3*) . (4*) . (5*) . const 1 $ () --

1* ( 2* ( 3* ( 4* ( 5* ( const 1 () ))))) factorial n = foldr (($) . (*)) 1 ..n= foldr ($) 1 $ map (*) ..n-- factorial 5

((1*) $) ( ((2*) $) ( ((3*) $) ( ((4*) $) ( ((5*) $) 1 )))) --

(1*) $ (2*) $ (3*) $ (4*) $ (5*) $ 1 --

1* ( 2* ( 3* ( 4* ( 5* 1 ))))


More examples


Hamming numbers

A remarkably concise function that returns the list of
Hamming numbers Regular numbers are numbers that evenly divide powers of 60 (or, equivalently, powers of 30). Equivalently, they are the numbers whose only prime divisors are 2, 3, and 5. As an example, 602 = 3600 = 48 ×&nb ...
in order: hamming = 1 : map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming Like the various fibs solutions displayed above, this uses corecursion to produce a list of numbers on demand, starting from the base case of 1 and building new items based on the preceding part of the list. Here the function union is used as an operator by enclosing it in back-quotes. Its case clauses define how it merges two ascending lists into one ascending list without duplicate items, representing sets as ordered lists. Its companion function minus implements
set difference In set theory, the complement of a set , often denoted by (or ), is the set of elements not in . When all sets in the universe, i.e. all sets under consideration, are considered to be members of a given set , the absolute complement of is the ...
: It is possible to generate only the unique multiples, for more efficient operation. Since there are no duplicates, there's no need to remove them: smooth235 = 1 : foldr (\p s -> fix $ mergeBy (<) s . map (p*) . (1:)) [] [2,3,5] where fix f = x where x = f x -- fixpoint combinator, with sharing This uses the more efficient function merge which doesn't concern itself with the duplicates (also used in the following next function, mergesort ): mergeBy less xs ys = merge xs ys where merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) , less y x = y : merge (x:xs) ys , otherwise = x : merge xs (y:ys) Each vertical bar ( , ) starts a
guard Guard or guards may refer to: Professional occupations * Bodyguard, who protects an individual from personal assault * Crossing guard, who stops traffic so pedestrians can cross the street * Lifeguard, who rescues people from drowning * Prison ...
clause with a ''guard expression'' before the = sign and the corresponding definition after it, that is evaluated if the guard is true.


Mergesort

Here is a bottom-up
merge sort In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, and comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the order of equal elements is the same i ...
, defined using the
higher-order function In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: * takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
until: mergesortBy less [] = [] mergesortBy less xs = head $ until (null . tail) (pairwise $ mergeBy less) [ , x <- xs] pairwise f (a:b:t) = f a b : pairwise f t pairwise f t = t


Prime numbers

The mathematical definition of
primes A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways ...
can be translated pretty much word for word into Haskell: -- "Integers above 1 that cannot be divided by a smaller integer above 1" -- primes = -- = primes = n <- .._all_(\d_->_rem_n_d_/=_0)_[2..(n-1).html" ;"title="..(n-1).html" ;"title=".. all (\d -> rem n d /= 0) [2..(n-1)">.. all (\d -> rem n d /= 0) [2..(n-1)">..(n-1).html" ;"title=".. all (\d -> rem n d /= 0) [2..(n-1)">.. all (\d -> rem n d /= 0) [2..(n-1) This finds primes by trial division. Note that it is not optimized for efficiency and has very poor performance. Slightly faster (but still very slow) is this code by David Turner (computer scientist), David Turner: primes = sieve .. where sieve (p:xs) = p : sieve x <- xs, rem x p /= 0 Much faster is the optimal trial division algorithm primes = 2 : n <- .. all ((> 0) . rem n) $ takeWhile ((<= n) . (^2)) primes or an unbounded
sieve of Eratosthenes In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime n ...
with postponed sieving in stages, primes = 2 : sieve primes .. where sieve (p:ps) (span (< p*p) -> (h, t)) = h ++ sieve ps (minus t *p, p*p+p.. or the combined sieve implementation by Richard Bird,O'Neill, Melissa E.
"The Genuine Sieve of Eratosthenes"
Journal of Functional Programming The ''Journal of Functional Programming'' is a peer-reviewed scientific journal covering the design, implementation, and application of functional programming languages, spanning the range from mathematical theory to industrial practice. Topics co ...
, Published online by Cambridge University Press 9 October 2008 , pp. 10, 11.
-- "Integers above 1 without any composite numbers which -- are found by enumeration of each prime's multiples" primes = 2 : minus .. (foldr (\(m:ms) r -> m : union ms r) [] p*p, p*p+p ..] , p <- primes]) or an even faster Fold (higher-order function)#Tree-like folds, tree-like folding variant with nearly optimal (for a list-based code) time complexity and very low space complexity achieved through telescoping multistage recursive production of primes: primes = 2 : _Y ((3 :) . minus ,7... _U . map (\p -> *p, p*p+2*p..) where -- non-sharing Y combinator: _Y g = g (_Y g) -- (g (g (g (g (...))))) -- big union ~= nub.sort.concat _U ((x:xs):t) = x : (union xs . _U . pairwise union) t Working on arrays by segments between consecutive squares of primes, it's import Data.Array import Data.List (tails, inits) primes = 2 : (r:q:_, px) <- zip (tails (2 : [p^2 , p <- primes) (inits primes), (n, True) <- assocs (accumArray (\_ _ -> False) True (r+1,q-1) [ (m,()) , p <- px , s <- [div (r+p) p*p] , m <- [s,s+p..q-1] ])] The shortest possible code is probably  nubBy (((>1) .) . gcd) [2..].  It is quite slow.


Syntax


Layout

Haskell allows
indentation __FORCETOC__ In the written form of many languages, an indentation or indent is an empty space at the beginning of a line to signal the start of a new paragraph. Many computer languages have adopted this technique to designate "paragraphs" or ot ...
to be used to indicate the beginning of a new declaration. For example, in a ''where'' clause: product xs = prod xs 1 where prod [] a = a prod (x:xs) a = prod xs (a*x) The two equations for the nested function prod are aligned vertically, which allows the semi-colon separator to be omitted. In Haskell, indentation can be used in several syntactic constructs, including do, let, case, class, and instance. The use of indentation to indicate program structure originates in
Landin Landin is a surname. Notable people with the surname include: * Peter J. Landin (1930–2009), British computer scientist * Mark Landin, municipality in Brandenburg, Germany * Niklas Landin Jacobsen (born 1988), Danish handballer * Luis Ángel La ...
's
ISWIM ISWIM (acronym for If you See What I Mean) is an abstract computer programming language (or a family of languages) devised by Peter Landin and first described in his article "The Next 700 Programming Languages", published in the Communications o ...
language, where it was called the
off-side rule A computer programming language is said to adhere to the off-side rule of syntax if blocks in that language are expressed by their indentation. The term was coined by Peter Landin, possibly as a pun on the offside rule in association football. ...
. This was later adopted by Miranda, and Haskell adopted a similar (but rather more complicated) version of Miranda's off-side rule, which is called "layout". Other languages to adopt whitespace-sensitive syntax include
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
and F#. The use of layout in Haskell is optional. For example, the function product above can also be written: product xs = prod xs 1 where The explicit open brace after the where keyword indicates that the programmer has opted to use explicit semi-colons to separate declarations, and that the declaration-list will be terminated by an explicit closing brace. One reason for wanting support for explicit delimiters is that it makes automatic generation of Haskell source code easier. Haskell's layout rule has been criticised for its complexity. In particular, the definition states that if the parser encounters a parse error during processing of a layout section, then it should try inserting a close brace (the "parse error" rule). Implementing this rule in a traditional
parsing Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. The term ''parsing'' comes from Lati ...
/ lexical-analysis combination requires two-way cooperation between the parser and lexical analyser, whereas in most languages these two phases can be considered independently.


Function calls

Applying a function f to a value x is expressed as simply f x. Haskell distinguishes function calls from infix operators syntactically, but not semantically. Function names which are composed of punctuation characters can be used as operators, as can other function names if surrounded with backticks; and operators can be used in prefix notation if surrounded with parentheses. This example shows the ways that functions can be called: add a b = a + b ten1 = 5 + 5 ten2 = (+) 5 5 ten3 = add 5 5 ten4 = 5 `add` 5 Functions which are defined as taking several parameters can always be partially applied. Binary operators can be partially applied using ''section'' notation: ten5 = (+ 5) 5 ten6 = (5 +) 5 addfive = (5 +) ten7 = addfive 5


List comprehensions

See List comprehension#Overview for the Haskell example.


Pattern matching

Pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
is used to match on the different constructors of algebraic data types. Here are some functions, each using pattern matching on each of the types below: -- This type signature says that empty takes a list containing any type, and returns a Bool empty :: -> Bool empty (x:xs) = False empty [] = True -- Will return a value from a Maybe a, given a default value in case a Nothing is encountered fromMaybe :: a -> Maybe a -> a fromMaybe x (Just y) = y fromMaybe x Nothing = x isRight :: Either a b -> Bool isRight (Right _) = True isRight (Left _) = False getName :: Person -> String getName (Person name _ _) = name getSex :: Person -> Sex getSex (Person _ sex _) = sex getAge :: Person -> Int getAge (Person _ _ age) = age Using the above functions, along with the map function, we can apply them to each element of a list, to see their results: map empty 1,2,3[],[2],[1.. -- returns [False,True,False,False] map (fromMaybe 0) [Just 2,Nothing,Just 109238, Nothing] -- returns [2,0,109238,0] map isRight [Left "hello", Right 6, Right 23, Left "world"] -- returns alse, True, True, False map getName erson "Sarah" Female 20, Person "Alex" Male 20, tom-- returns Sarah", "Alex", "Tom" using the definition for tom above * Abstract Types * Lists


Tuples

Tuples In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
in haskell can be used to hold a fixed number of elements. They are used to group pieces of data of differing types: account :: (String, Integer, Double) -- The type of a three-tuple, representing -- a name, balance, and interest rate account = ("John Smith",102894,5.25) Tuples are commonly used in the zip* functions to place adjacent elements in separate lists together in tuples (zip4 to zip7 are provided in the Data.List module): -- The definition of the zip function. Other zip* functions are defined similarly zip :: -> -> x,y)zip (x:xs) (y:ys) = (x,y) : zip xs ys zip _ _ = [] zip [1..5] "hello" -- returns [(1,'h'),(2,'e'),(3,'l'),(4,'l'),(5,'o')] -- and has type [(Integer, Char)] zip3 [1..5] "hello" [False, True, False, False, True] -- returns [(1,'h',False),(2,'e',True),(3,'l',False),(4,'l',False),(5,'o',True)] -- and has type Integer,Char,Bool) In the GHC compiler, tuples are defined with sizes from 2 elements up to 62 elements. *
Records A record, recording or records may refer to: An item or collection of data Computing * Record (computer science), a data structure ** Record, or row (database), a set of fields in a database related to one entity ** Boot sector or boot record, ...


Namespaces

In the section above, calc is used in two senses, showing that there is a Haskell type class namespace and also a namespace for values: #a Haskell
type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
for calc. The
domain Domain may refer to: Mathematics *Domain of a function, the set of input values for which the (total) function is defined **Domain of definition of a partial function **Natural domain of a partial function **Domain of holomorphy of a function * Do ...
and
range Range may refer to: Geography * Range (geographic), a chain of hills or mountains; a somewhat linear, complex mountainous or hilly area (cordillera, sierra) ** Mountain range, a group of mountains bordered by lowlands * Range, a term used to i ...
can be explicitly denoted in a Haskell type class. #a Haskell value, formula, or expression for calc.


Typeclasses and polymorphism


Algebraic data types

Algebraic data types In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite type, i.e., a type formed by combining other types. Two common classes of algebraic types are product types (i.e., t ...
are used extensively in Haskell. Some examples of these are the built in list, Maybe and Either types: -- A list of a's ( is either an a consed (:) onto another list of a's, or an empty list ([]) data = a : , [] -- Something of type Maybe a is either Just something, or Nothing data Maybe a = Just a , Nothing -- Something of type Either atype btype is either a Left atype, or a Right btype data Either a b = Left a , Right b Users of the language can also define their own
abstract data type In computer science, an abstract data type (ADT) is a mathematical model for data types. An abstract data type is defined by its behavior (Semantics (computer science), semantics) from the point of view of a ''User (computing), user'', of the dat ...
s. An example of an ADT used to represent a person's name, sex and age might look like: data Sex = Male , Female data Person = Person String Sex Int -- Notice that Person is both a constructor and a type -- An example of creating something of type Person tom :: Person tom = Person "Tom" Male 27


Type system

*
Type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
es * Type defaulting * Overloaded Literals * Higher Kinded Polymorphism * Multi-Parameter Type Classes * Functional Dependencies


Monads and input/output

* Overview of the monad framework * Applications ** Monadic IO ** Do-notation ** References ** Exceptions


ST monad

The ST monad allows programmers to write imperative algorithms in Haskell, using mutable variables (STRefs) and mutable arrays (STArrays and STUArrays). The advantage of the ST monad is that it allows programmers to write code that has internal side effects, such as destructively updating mutable variables and arrays, while containing these effects inside the monad. The result of this is that functions written using the ST monad appear completely pure to the rest of the program. This allows programmers to produce imperative code where it may be impractical to write functional code, while still keeping all the safety that pure code provides. Here is an example program (taken from the Haskell wiki page on th
ST monad
that takes a list of numbers, and sums them, using a mutable variable: import Control.Monad.ST import Data.STRef import Control.Monad sumST :: Num a => -> a sumST xs = runST $ do -- runST takes stateful ST code and makes it pure. summed <- newSTRef 0 -- Create an STRef (a mutable variable) forM_ xs $ \x -> do -- For each element of the argument list xs .. modifySTRef summed (+x) -- add it to what we have in n. readSTRef summed -- read the value of n, which will be returned by the runST above.


STM monad

The STM monad is an implementation of
Software Transactional Memory In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM ...
in Haskell. It is implemented in the GHC compiler, and allows for mutable variables to be modified in transactions.


Arrows

* Applicative Functors * Arrows As Haskell is a pure functional language, functions cannot have side effects. Being non-strict, it also does not have a well-defined evaluation order. This is a challenge for real programs, which among other things need to interact with an environment. Haskell solves this with '' monadic types'' that leverage the type system to ensure the proper sequencing of imperative constructs. The typical example is I/O, but monads are useful for many other purposes, including mutable state, concurrency and transactional memory, exception handling, and error propagation. Haskell provides a special syntax for monadic expressions, so that side-effecting programs can be written in a style similar to current imperative programming languages; no knowledge of the mathematics behind monadic I/O is required for this. The following program reads a name from the command line and outputs a greeting message: main = do putStrLn "What's your name?" name <- getLine putStr ("Hello, " ++ name ++ "!\n") The do-notation eases working with monads. This do-expression is equivalent to, but (arguably) easier to write and understand than, the de-sugared version employing the monadic operators directly: main = putStrLn "What's your name?" >> getLine >>= \ name -> putStr ("Hello, " ++ name ++ "!\n") : ''See also wikibooks:Transwiki:List of hello world programs#Haskell for another example that prints text.''


Concurrency

The Haskell language definition itself does not include either
concurrency Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
or parallelism, although GHC supports both.
Concurrent Haskell Concurrent Haskell extends Haskell 98 with explicit concurrency. Its two main underlying concepts are: * A primitive type MVar α implementing a bounded/single-place asynchronous channel, which is either empty or holds a value of type α. * The ...
is an extension to Haskell that provides support for threads and synchronization.Simon Peyton Jones, Andrew Gordon, and Sigbjorn Finne
Concurrent Haskell
''ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (PoPL).'' 1996. (Some sections are out of date with respect to the current implementation.)
GHC's implementation of Concurrent Haskell is based on multiplexing lightweight Haskell threads onto a few heavyweight OS threads,Runtime Support for Multicore Haskell
(Simon Marlow, Simon Peyton Jones, Satnam Singh) ICFP '09: Proceedings of the 14th ACM SIGPLAN international conference on Functional programming, Edinburgh, Scotland, August 2009
so that Concurrent Haskell programs run in parallel on a
multiprocessor Multiprocessing is the use of two or more central processing units (CPUs) within a single computer system. The term also refers to the ability of a system to support more than one processor or the ability to allocate tasks between them. There ar ...
. The runtime can support millions of simultaneous threads. The GHC implementation employs a dynamic pool of OS threads, allowing a Haskell thread to make a blocking system call without blocking other running Haskell threads.Extending the Haskell Foreign Function Interface with Concurrency
(Simon Marlow, Simon Peyton Jones, Wolfgang Thaller) Proceedings of the ACM SIGPLAN workshop on Haskell, pages 57--68, Snowbird, Utah, USA, September 2004
Hence the lightweight Haskell threads have the characteristics of heavyweight OS threads, and the programmer is unaware of the implementation details. Recently, Concurrent Haskell has been extended with support for
Software Transactional Memory In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based synchronization. STM ...
(STM), which is a concurrency abstraction in which compound operations on shared data are performed atomically, as transactions.{{cite conference , first1 = Tim , last1 = Harris , first2 = Simon , last2 = Marlow , first3 = Simon , last3 = Peyton-Jones , first4 = Maurice , last4 = Herlihy , citeseerx = 10.1.1.67.3686 , title = Composable memory transactions , book-title = Proceedings of the tenth ACM SIGPLAN symposium on Principles and practice of parallel programming , year = 2005 GHC's STM implementation is the only STM implementation to date to provide a static compile-time guarantee preventing non-transactional operations from being performed within a transaction. The Haskell STM library also provides two operations not found in other STMs: retry and orElse, which together allow blocking operations to be defined in a modular and composable fashion.


References

Haskell programming language family Articles with example Haskell code