Haskell Basics

By Xah Lee. Date:

warning: this page is incomplete and abandoned.

Important ghci commands:

:load ‹file name›
:reload
:edit ‹file name›
:type «expression»
:?              show all commands

Names

Name must start with lower letter.

String

-- strings
"this is a string"

--converting a string to number, use “read”
read "7" + 2

--converting a number to string, use “show”
show 2 ++ "7"

-- Char.toUpper

Lists

-- a list
[3,9,2]

[] -- empty list ok

-- length
length [ 1, 2, 3, 4, 5 ] -- gives the num of elements

-- prepending to list
4:[3,9,2]

-- join two lists
[2,3]++[4,5] -- returns [2,3,4,5]

-- taking elements
[0,1,2,3]!!2 -- gives the 2nd element. (count starts at 0)

head [1,2,3] -- returns the first element
tail [1,2,3] -- rest elements

take 3 [ 1, 2, 3, 4, 5 ] -- takes the first n elements
drop 3 [ 1, 2, 3, 4, 5 ] -- removes the first n elements

reverse [1,2,6] -- reverses list
-- n-tuples
(7,"hi")
(7,"hi",8)

--getting the first element of a list
fst (7, "hi")

--getting the second element
snd (7,"hi")
map (^2) [1,2,3,4]

filter odd [1,2,3,4]

foldr (-) 0 [1,2,3,4]
foldl (-) 0 [1,2,3,4]

In order for a program to be executable, it must have a module name named “Main”, and it must contain a function named “main”. Also, in general module name must agree with file name.

2006-02