An advanced, purely functional programming language

TODO
  1. hackage.haskell.org/package/data-aviary-0.4.0/docs/Data-Aviary-Birds.html

  2. stackoverflow.com/questions/39628091/defining-a-function-for-multiple-types

  3. learnyouahaskell.com/types-and-typeclasses

  4. wiki.haskell.org/Constructor

  5. en.wikibooks.org/wiki/Haskell/Variables_and_functions

  6. www.tutorialspoint.com/haskell/haskell_functions.htm

  7. learnyouahaskell.com/syntax-in-functions

  8. Record pattern matching e.g. f P{name=n} = n

  9. wiki.haskell.org/Case

  10. zvon.org/other/haskell/Outputsyntax/caseQexpressions_reference.html

  11. www.haskell.org/tutorial/numbers.html

  12. wiki.haskell.org/Converting_numbers

  13. wiki.haskell.org/Declaration_vs._expression_style

  14. learnyouahaskell.com/higher-order-functions#function-application

  15. wiki.haskell.org/Let_vs._Where

  16. wiki.haskell.org/Type

  17. en.wikibooks.org/wiki/Haskell/Type_declarations

  18. hackage.haskell.org/package/constraints-0.13.4/docs/Data-Constraint.html

  19. typeOf

  20. downloads.haskell.org/ghc/latest/docs/users_guide/

  21. Guards |

  22. Underscore _

  23. Apostrophe in names

  24. en.wikibooks.org/wiki/Haskell/Control_structures

  25. wiki.haskell.org/If-then-else

  26. wiki.haskell.org/Pure

  27. wiki.haskell.org/Memoization

  28. wiki.haskell.org/Means_of_expression

  29. conal.net/blog/posts/everything-is-a-function-in-haskell

  30. wiki.haskell.org/Import_modules_properly

  31. wiki.haskell.org/Import

  32. wiki.haskell.org/Pointfree

  33. wiki.haskell.org/Comparison_chain

  34. hoogle.haskell.org/

  35. hackage.haskell.org/package/probability-0.2.8/docs/Numeric-Probability-Distribution.html

  36. dennybritz.com/posts/probability-monads-from-scratch/

  37. www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/13-the-list-monad

  38. wiki.haskell.org/All_About_Monads

  39. Monads for functional programming by Philip Wadler

  40. www.adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html

  41. wiki.haskell.org/Debugging

  42. downloads.haskell.org/~ghc/8.6.5/docs/html/users_guide/ghci.html#the-ghci-debugger

  43. ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/pattern_synonyms.html

References

Basics

So far, if I could pick just one resource from which to learn Haskell, it would be the [haskell-wikibook].

$ curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh
Start Haskell REPL (interactive session)
$ ghci
Comment Text Until the End of a Line
ghci> -- Double dash makes comment up to the end of the line.

Evaluation of Expressions

Because Haskell is a purely functional language, all computations are done via the evaluation of expressions (syntactic terms) to yield values
[a-gentle-introduction-to-haskell]
chapter 2 Values, Types, and Other Goodies
Expression False yields boolean value False.
ghci> False
False
Expression [] yields empty list [].
ghci> []
[]
Expression [ False , True ] yields list [False,True].
ghci> [ False  ,   True    ]
[False,True]

Types

NOTE

:type is one of GHCi commands.

Value False has type (::) boolean type (Bool).
ghci> :type False
False :: Bool
Empty list ([]) has type (::) list of type a ([a]).
ghci> :type []
[] :: [a]
List with False value ([False]) has type (::) list of booleans ([Bool]).
ghci> :type [False]
[False] :: [Bool]
Zero (0) has type (::) type a constrained (=>) to be instance of class Num (Num a).
ghci> :type 0
0 :: Num a => a
List of three numbers ([1,2,3]) has type (::) list of type a ([a]) constrained (=>) to be instance of class Num (Num a).
ghci> :type [1,2,3]
[1,2,3] :: Num a => [a]
Nullary kind
ghci> :kind Bool
Bool :: *
ghci> :kind [Bool]
[Bool] :: *
ghci> :kind [] Bool
[] Bool :: *
ghci> :kind (Bool -> Bool)
(Bool -> Bool) :: *
ghci> :kind (->) Bool Bool
(->) Bool Bool :: *
Unary kind
ghci> :kind []
[] :: * -> *
ghci> :kind (->) Bool
(->) Bool :: * -> *
Binary kind
ghci> :kind (->)
(->) :: * -> * -> *

Lazy Evaluation

Generate list of numbers from 1 to 10 inclusive.
ghci> [1..10]
[1,2,3,4,5,6,7,8,9,10]
Take the first 10 values from infinite sequence of numbers starting with 1.
ghci> take 10 [1..]
[1,2,3,4,5,6,7,8,9,10]
Because Haskell is lazy, it won’t try to evaluate the infinite list immediately because it would never finish. It’ll wait to see what you want to get out of that infinite lists.

Function Application

Function application is denoted by juxtaposition and associates to the left. Thus, f x y is parsed (f x) y.
ghci> take 10 [1..]
[1,2,3,4,5,6,7,8,9,10]
ghci>
ghci> (take 10) [1..]
[1,2,3,4,5,6,7,8,9,10]

Function Type

Function not has type (::) applied to boolean (Bool) returns (->) boolean (Bool).
ghci> :type not
not :: Bool -> Bool
Function not applied to value True returns False.
ghci> not True
False

Currying

a function of two arguments may be represented as a function of one argument that itself returns a function of one argument.
Function take has type (::) applied to Int returns (->) function with type [a] -> [a].
ghci> :type take
take :: Int -> [a] -> [a]
Definition of takeFirst10 by application of function take to the number 10.
ghci> takeFirst10 = take 10
ghci> :type takeFirst10
takeFirst10 :: [a] -> [a]
ghci>
ghci> takeFirst10 [1..]
[1,2,3,4,5,6,7,8,9,10]

Infix Operators

[Lexically, infix operators consist entirely of "symbols," as opposed to normal identifiers which are alphanumeric (§2.4). Haskell has no prefix operators, with the exception of minus (-), which is both infix and prefix.]
[a-gentle-introduction-to-haskell]
chapter 3 Functions
Infix Operator Examples
ghci> 0 - 1
-1
ghci> 10 ^ 2
100
ghci> 0 : []
[0]
ghci> 1 : 0 : []
[1,0]
ghci> [0] ++ [1]
[0,1]
ghci> ['a'..] !! 9
'j'
A section is a partial application of an infix operator to no arguments, the left argument, or the right argument—and by surrounding the result in parentheses
Sections
ghci> power = (^)
ghci> 2 `power` 3
8
ghci> power 2 3
8
ghci>
ghci> cube = (^3)
ghci> cube 2
8
ghci>
ghci> powerOf2 = (2^)
ghci> powerOf2 3
8
WARNING

(-42) equals to -42 not to a function that subtracts 42. In order to get the later, write (subtract 42)

There are very few predefined “operators” in Haskell - most that do look predefined are actually syntax (e.g., “=”). Instead, operators are simply functions that take two arguments and have special syntax support.

Allowable symbols which can be used to define operators are:

# $ % & * + . / < = > ? @ \ ^ | - ~

However, there are several “operators” which cannot be redefined. They are: <-, -> and =. The last, =, cannot be redefined by itself, but can be used as part of multi-character operator.

Precedence and Associativity

A fixity declaration can be given for any infix operator or constructor (including those made from ordinary identifiers, such as elem). This declaration specifies a precedence level from 0 to 9 (with 9 being the strongest; normal application is assumed to have a precedence level of 10), and left-, right-, or non-associativity.
[a-gentle-introduction-to-haskell]
chapter 3 Functions
If no fixity declaration is given for a particular operator, it defaults to infixl 9.
[a-gentle-introduction-to-haskell]
chapter 3 Functions
Fixity information can be can be obtained using :info command in ghci.
ghci> :info /
type Fractional :: * -> Constraint
class Num a => Fractional a where
  (/) :: a -> a -> a
  ...
  	-- Defined in ‘GHC.Real’
infixl 7 /

Fixity infixl 7 / means infix operator, left associativity, precedence 7.

Left Associativity
ghci> 1 / 2 / 3
0.16666666666666666
ghci> (1 / 2) / 3
0.16666666666666666
ghci> 1 * 2 / 3
0.6666666666666666
Right Associativity
ghci> 3 ^ 2 ^ 1 ^ 0
9
ghci> 3 ^ (2 ^ (1 ^ 0))
9
ghci> ((3 ^ 2) ^ 1) ^ 0
1
Definition of division operator /// with right associativity in file RightDivision.hs
module RightDivision ((///)) where

infixr  7 ///
(///) :: Fractional a => a -> a -> a
a /// b = a / b
Load RightDivision.hs and use /// operator.
ghci> :load RightDivision
[1 of 1] Compiling RightDivision    ( RightDivision.hs, interpreted )
Ok, one module loaded.
ghci> 1 /// 2 /// 3
1.5
Different associativities of the same precedence operators leads to a parsing error.
ghci> 1 /// 2 * 3

<interactive>:6:1: error:
    Precedence parsing error
        cannot mix ‘///’ [infixr 7] and ‘*’ [infixl 7] in the same infix expression

Modules

A Haskell program is a collection of modules, one of which, by convention, must be called Main and must export the value main.
[haskell-2010] Chapter 5 Modules
A module begins with a header: the keyword module, the module name, and a list of entities (enclosed in round parentheses) to be exported. The header is followed by a possibly-empty list of import declarations (impdecls, Section 5.3) that specify modules to be imported, optionally restricting the imported bindings. This is followed by a possibly-empty list of top-level declarations (topdecls, Chapter 4).
[haskell-2010] Chapter 5 Modules
Example of module Main header
Following header creates module Main, which exports function main.
module Main(main) where

This exact header is inserted as a first line, if other header is omitted.

For more information, see en.wikibooks.org/wiki/Haskell/Modules.

base: Basic libraries

This package contains the Standard Haskell Prelude and its support libraries, and a large collection of useful libraries ranging from data structures to parsing combinators and debugging utilities.

Prelude

There is one distinguished module, Prelude, which is imported into all modules by default
[haskell-2010] Chapter 5 Modules

Simple combinators working solely on and with functions.

  1. Identity function id

  2. Constant function const

  3. Function composition. (.)

  4. Flip function flip

  5. Function application operator ($)

  6. Reverse application operator (&)

  7. fix is the least defined x such that f x = x

  8. on b u x y runs the binary function b on the results of applying unary function u to two arguments x and y.

Minimal complete definition: fmap
class Functor f where
        fmap :: (a -> b) -> f a -> f b
A minimal complete definition must include implementations of pure and of either <*> or liftA2
class Functor f => Applicative f where
        pure :: a -> f a
        (<*>) :: f (a -> b) -> f a -> f b
Minimal complete definition (>>=)
class Applicative m => Monad m where
        (>>=) :: forall a b. m a -> (a -> m b) -> m b

Do Expressions

A do expression provides a more conventional syntax for monadic programming. It allows an expression such as

putStr "x: "    >>
getLine         >>= \l ->
return (words l)

to be written in a more traditional way as:

do putStr "x: "
   l <- getLine
   return (words l)
[haskell-2010]
3.14 Do Expressions
ap                :: (Monad m) => m (a -> b) -> m a -> m b
ap m1 m2          = do { x1 <- m1; x2 <- m2; return (x1 x2) }
Minimal complete definition: (<>) | sconcat
class Semigroup a where
        (<>) :: a -> a -> a
Minimal complete definition: mempty | mconcat
class Semigroup a => Monoid a where
        mempty :: a
Minimal complete definition foldMap | foldr
class Foldable t where
        foldMap :: Monoid m => (a -> m) -> t a -> m
Minimal complete definition traverse | sequenceA
class (Functor t, Foldable t) => Traversable t where
        traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

Packages

Hackage is the Haskell community’s central package archive of open source software. Hackage has been online since January 2007 and is constantly growing.
containers: Assorted concrete container types

This package contains efficient general-purpose implementations of various immutable container types including sets, maps, sequences, trees, and graphs.

safe: Library of safe (exception free) functions

A library wrapping Prelude/Data.List functions that can throw exceptions, such as head and !!. Each unsafe function has up to four variants

lens: Lenses, Folds and Traversals

The combinators in Control.Lens provide a highly generic toolbox for composing families of getters, folds, isomorphisms, traversals, setters and lenses and their indexed variants.

repa: High performance, regular, shape polymorphic parallel arrays.

Repa provides high performance, regular, multi-dimensional, shape polymorphic parallel arrays.

array: Mutable and immutable arrays

In addition to providing the Data.Array module as specified in the Haskell 2010 Language Report, this package also defines the classes IArray of immutable arrays and MArray of arrays mutable within appropriate monads, as well as some instances of these classes.