







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Today’s Topics ...
String values are surrounded by double quotes
Prelude> "Hello World!" "Hello World!"
Prelude> ’a’ ’a’
Prelude> ’abc’
Prelude> :type ’a’ ’a’ :: Char
Prelude> :type "abc" "abc" :: [Char]
The Prelude defines many list functions
Two really useful ones are:
Prelude> head [4, 1, 5, 3] 4
Prelude> head [] *** Exception: Prelude.head: empty list
Prelude> tail [4, 1, 5, 3] [1, 5, 3]
Prelude> tail [1] []
Prelude> tail [] *** Exception: Prelude.tail: empty list
Prelude> null [] True
Prelude> null [1, 2] False
Prelude> init [4, 1, 5, 3] [4, 1, 5]
Prelude> init [1] []
Prelude> init [] *** Exception: Prelude.init: empty list
Prelude> reverse [4, 1, 5, 3] [3, 5, 1, 4]
Prelude> reverse [1] [1]
Prelude> reverse [] []
Prelude> elem 1 [4, 1, 5, 3] True
Prelude> elem 0 [4, 1, 5, 3] False
Prelude> elem ’a’ [4, 1, 5, 3]
We’ll look at more later ...
A “tuple” is a fixed size collection of values
Prelude> (1964, "Fist Full of Dollars") (1964, "Fist Full of Dollars")
Prelude> :type (True, "yes") (True, "yes") :: (Bool, [Char])
The special “unit” tuple
Prelude> () ()
Prelude> :type () () :: ()
There are no one-valued tuples in Haskell
Prelude> :type ("hello") ("hello") :: [Char]
Getting data out of tuples is not so easy
Prelude> fst (1, True) 1
Prelude> snd (1, True) True
Prelude> fst (1, True, "hello")
We can define our own functions to do this ...
Functions can be defined in ghci using let
Prelude> let f p 1 p 2... pn = e
A simple example:
Prelude> let add x y = x + y
Usually more convenient to use source files
-- ex1.hs -- add function add x y = x + y
Prelude> :load ex [1 of 1] Compiling Main ( example.hs, interpreted ) Ok, modules loaded: Main. *Main> add 3 4 7
Example: Define an avg3 function
avg3 x y z = (x + y + z)/3 -- indentation required
Example: Accessing tuple elements
fst3 (x, y, z) = x
Prelude> fst3 (’a’, ’b’, ’c’) ’a’
snd3 (x, y, z) = y
Prelude> snd3 (’a’, ’b’, ’c’) ’b’
Example: listify
listify x = [x] -- e.g., listify 5 => [5]