Haskell

From Organic Design wiki
Revision as of 22:45, 5 March 2021 by Saul (talk | contribs) (Types: Structured data.)

Haskell is a functional programming langauge used in Cardano.

Getting Started

Install the Haskell platform with:

sudo apt-get install haskell-platform

Then run the interpreter via:

ghci

Quitting the Haskell interpreter is the same as vim: :q or :quit.


You can write Haskell in .hs files then compile using ghc like so:

ghc -o hello hello.hs

And then you can run via the executable file ./hello.

Types

Haskell allows you to define types but this is optional if no type is declared it will infer the type. Types in Haskell must start with a capital letter.

5 -- Infers the type
5 :: Double -- Define the type.

-- Ask ghci what type '5' is.
:t 5

The unit type () is a type that has only one value () which is similar to void in other languages.

You can combine types easily in one of two ways: Tuples and Lists. Lists hold many values of the same type whereas Tuples can hold values of different types.

[1, 2, 3] -- Simple list with the values 1 to 3.
[1 .. 5] -- List with the values 1 to 5
[1, 3 .. 10] -- List of odd values between 1 and 10.
['H', 'e', 'l', 'l', 'o'] -- A String!

(1, true) -- Simple Tuple.
(1, True, 2.0, 2) -- A longer Tuple

zip [1 .. 5] ['a' .. 'e'] -- Combine the two lists into a list of tuples: [(1, 'a'), (2, 'b') ...]
map (+ 2) [1 .. 5] -- Map function on a list: [3,4,5,6,7]
filter (> 2) [1 .. 5] -- Filter function on a list: [3,4,5]
fst (1, 2) -- Get the first element of the Tuple.
snd (1, 2) -- Get the second element of the Tuple.
map fst [(1, 2), (3, 4), (5, 6)] -- Apply the first function to each tuple in the list: [1,3,5].

See Also