0% found this document useful (0 votes)
7 views27 pages

4 Basic Data Types

Uploaded by

striveemashava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

4 Basic Data Types

Uploaded by

striveemashava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

BASIC DATA TYPES

Functional Programming CUCE211


Outline
• Recap
• Type variables
• Type Classes
• Lists
• Tuples
• Strings
Recap
• Haskell provides the following pre-defined types
• Char, Bool, Int, Integer (for very large numbers), Float, and Double,
[] (for lists), () (for tuples)
Type Variables
• Normal types such as Char are instantiated with values such as ‘t’, ‘Z’, etc.

• We have also defined functions for parameters of specific types, e.g.


trebleMe::Int -> Int
trebleMe x = x + x + x

• However, we can be non-explicit on the types so that a function can work on


values of varied forms/types.

• For example, a function that returns the last element in a set will return a float
if it is a set of floats, an integer if it is a set of integers, a character if it is a set
of characters, an d so on.
• It would make programming unproductive if for such a scenario one has to
define 3 different functions that perform the same action for different types.
• Make use of type variables instead
Type variables cont’d
• Type variables are represented using a lowercase letter of the English
alphabet.

• The function retLast for returning the last element of a list would have a
signature such as
• retLast :: [a] -> a

• Meaning retLast processes a list of values with type a and returns a value
of the type a.

• We can state however the properties of the type variable using type
classes,
• Is a any number or whole number, or fraction?
• Can it be ordered?

• Many functions are generic in nature.


Type classes
• Functions can be grouped together into a type
class
• Define some behaviour
• An instance of that class implements that
behaviour

• For example, the functions for comparing two


values against each other are grouped into a
pre-defined class called Ord.
• These functions are <, >, <=, and >=
Type classes cont’d
• The link Directory listing for base-4.12.0.0 documentation |
Hackage (haskell.org) has more information on Haskell type
classes and libraries.

• Type Classes are a flexible concept


• Programmers can define their own type classes.
• Programmers can also define new data types as instances
of these type classes.
• We will explore how to do this when considering user-
defined types much later.

• In the following slides, we look at some of the pre-defined


Type Classes.
Eq & Ord
Type Class Purpose Signature Example @ ghci
Eq Tests for equality (==) :: (Eq a) => a -  18.7 == 17.8
using == and /= > a -> Bool False
Ord Tests for ordering (>) :: (Ord a) => a -  "Donna" <
Uses <, >, >=, <=, > a -> Bool "Judith"
`compare` , max,
True
min
Outputs True/False
OR LT, GT and EQ for  12 `compare`
less-than, greater- 18
than and equal. LT
Show & Read
Type Class Purpose Signature Example @ ghci
Show Prints given value as a string. show 58
All data types we have met "58"
can be represented as strings.
Visit Text.Show (haskell.org)
for full documentation on the
data types.
Read Takes a string and returns a read :: (Read a) =>  read "True"
value whose type is an String -> a || False
instance of Read. Read does
True
the reverse of Show.
We can also ensure that Read  read "5.1" +
converts to a particular type 2.1
by specifying the required 7.2
data type  read "5" ::
Int
5
 (read "5" ::
Float) +2.1
7.1
ENUM & Bounded
Type Class Purpose Signature Example @ ghci
Enum Operations for Sequentially  ['a'..'c']
ordered types (e.g. (), Bool, Char, "abc"
Ordering, Int)  [2 .. 6]
They can also make use of the
pred and succ functions. [2,3,4,5,6]
Given an incompletely specified  pred 'Z'
list or item, this type class fills out 'X'
the entire list using values of
sequential ordering.
Bounded Finds the upper and lower bound minBound:: (Bounded  maxBound ::
for specified types using a) => a Bool
minBound, and maxBound.
True
For Int, Char, and Bool.types
minBound and maxBound will  minBound ::
return values according to the Bool
types. False
NUM, Float & Integral
Type Class Purpose Example @ ghci
Num Instances of this type can act like numbers,  20 :: Integer
e.g. Int, Integer, Float, or Double. The type 20
safety constraints mean statements need to  20 :: Float
be carefully written. (4 :: Int) * (2 :: Integer)
will result in a type error, while 4 * (2 :: 20.0
Integer) will compile since 4 will be  4 * (2 ::
converted to a number type that matches Integer)
2::Integer. 8
Floating This includes both Float and Double and Exercise: write statements
functions such as cos, log, pi have their that find the cosine and sine
results represented as Float. of certain values.

Integral This class is a numeric class for types of  fromIntegral


whole numbers only such as Int, Integer. (length
Functions such as fromIntegral convert an
[1,2,3,4]) + 3.2
integral number into a general number.
7.2
Function declaration example
• To declare a function that only calculates an inverse of
fractional values only and produces any other numerical
result, we could write:

findInv:: (Floating a)=> a -> b

findInv’:: (Floating a, Num b)=> a -> b

min :: Ord a => a -> a -> a


Exercise
• Find out the restrictions of making one type an instance of another
type.
• Give examples in your answer.
Hierarchy of Type Classes
MORE DATA TYPES
Lists
• A data structure that contains items of the same type
• indicated by [ ]
• An empty list is denoted as [ ]
• A delimited list of numbers e.g.
• [1,2,3,4,5,6]
• A named list of items e.g.
• let monopoly = [1,2,3,4,5,6]
• A list specified as ranges e.g.
• [1..10]
• [3,6,..40]
• [15,14..1]
• A list specifying multi-dimensional information e.g.
• [[1,2], [3,4], [5,6]]
• [[0,1,2], [0,3,4], [0,5,6]]
Operations on Lists
Function Example Result
++ ['h','e','l'] ++ ['h','e','l‘,'l','o']
['l','o']
: ['l','o'] : ['l','o‘,'h','e','l']
['h','e','l']
!! ['l','o‘,'h','e','l'] ‘h’
!! 2
==, <, <=, >= and > [1,2,3] < [1,3,4] True
head, tail, last, init, head [1,2,3] 1
null, length, reverse Tail [1,2,3] [2,3]
maximum, minimum, maximum [1,3,4] 4
product, sum sum [1,3,4] 8
take take 3 [1,2,8,3,5,6] [1,2,8]
drop drop 3 [1,2,8,3,5,6] [3,5,6]
drop 100 []
[1,2,8,3,5,6]
Working with Infinite Lists (1)
• Specified using first two items only
• E.g. [2,4..]

• Require their size to be cut so that they can be displayed


• Bounds specified by functions that use these lists
• Rely on Haskell’s lazy evaluation
• E.g. of cutting
• take 10 [2,4,..] returns a list of the first 10 items of the infinite
list.
Working with infinite lists (2)
• Can be produced using the functions cycle, repeat and replicate
• cycle replicates a lists elements indefinitely to form an infinite list,
• repeat is the cycling of a single element list hence it produces an infinite
list containing that one item
• replicate constructs a list of a specified length consisting of replications
of a single item.

• The results of cycle and repeat need to be cut so that they are displayable.
E.g.
• take 10 (cycle [5,2,1]) produces [5,2,1,5,2,1,5,2,1,5]
• take 10 (repeat 5) produces [5,5,5,5,5,5,5,5,5,5]
• replicate 10 5 produces [5,5,5,5,5,5,5,5,5,5]
Transforming, Filtering and Combining Lists (1)
• Use List Comprehension statements
• Statements similar to set comprehension statements

• Examples

• [x | x <- [1..10]]
• means construct a list of the pattern x, where x is drawn from the
list [1..10]
• Hence the values of the list become [1,2,3,4,5,6,7,8,9,10].

• To construct a list of the first 10 multiples of 2, we write


• [x*2 | x <- [1..10]]
• and obtain the list [2,4,6,8,10,12,14,16,18,20].
Transforming, Filtering and Combining Lists (2)
• To construct a list of multiples of 2 that are less than 10, we add this
restriction (called constraint or predicate) to the previous statement
and write
• [x*2 | x <- [1..10], x*2 < 10] to get [2,4,6,8].
• This last statement of specifying constraints or predicates on the
results is called filtering.

• As many predicates can be included, dependent on the problem.

• Predicates are separated by commas and lists will be evaluated


against these predicates by the interpreter accordingly.
• take 10 (cycle [5,2,1]) produces [5,2,1,5,2,1,5,2,1,5]
• take 10 (repeat 5) produces [5,5,5,5,5,5,5,5,5,5]
• replicate 10 5 produces [5,5,5,5,5,5,5,5,5,5]
Exercise
• Define a function that takes a list of numbers as a parameter and
replicates each item 3 times if the number is greater than 10,
otherwise it replicates the item 0 times.
repl::[Int]->[Int]
repl m = [ replicate 3 x | x <- m, x>10]

• Alternatively we can have:


repl x:xs = concat ((if (x>10) replicate 3 x else
replicate 7 x) : repl xs)

• Without using ghci, what do you expect to get as output for


[x*y | x <- [1,3], y <- [4,17,21]] ? Please explain your
answer.
Tuples (1)
• A structure used to group different types of information or to represent
multi-dimensional information
• Denoted in ( )
• A tuple of same type values
• (1,2)
• A tuple of different type values
• (‘a’, [1,2,3]) for the identifier and measures (length, width,
height) of an object
• (“084b”, 3.75, 234) for the code, price and quantity of an
item in stock
• (“domdom”, 15, 1987, 48.2) for a single person, e.g. their
name, day of birth, year of graduation and weight respectively.
• Pair = tuple of size 2, and triple = tuple of size 3.
Tuples (2)
• A list of tuples
• [(1,2), (2,3), (3,4)] can be considered as an example of a list of
vectors.
• Can be constructed using the zip function.
• zip [1,2,3,4,5] [6,7,8,9,10] produces [(1,6),(2,7),(3,8),
(4,9),(5,10)]

• Try the zip on one finite list and one infinite list. When does it
stop?
• ONLY Pre-defined functions for pairs
• fst (1,2) for returning the first component of a tuple
• snd (1,2) for returning the second component of a tuple
Practice on Lists and Tuples
See you in the Afternoon!
Strings
• A string is a sequence of characters
• It is a type alias for [Char].
• Real-world applications use Text or ByteString.
• Text is represented as a packed array of Unicode characters.
• This is similar to how most other high-level languages represent strings,
and gives much better time and space efficiency than the list version.

• One can define string constants. E.g.


• companyName :: String
• companyName = "Chinhoyi University of Technology“

• Strings (represented as [Char]) can be manipulated using functions for lists.


• Some useful functions include
• lines, unlines, words
Now We’re Up for More
Challenges with Strings!
See you in the Afternoon!

You might also like