4 Basic Data Types
4 Basic Data 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?
• 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].
• 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.