This repository has been archived on 2025-07-20. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
fp/02-polymorphic_functions.hs

83 lines
No EOL
2.3 KiB
Haskell

-- Polymorphic functions
-- =====================
-- 2023-10-04, 0900-1100, Martin Escardo
-- List length
-- ===========
length' :: [a] -> Int -- a list of an elements to an Int
length' = undefined
-- Concat two lists
-- ================
-- with concrete types
appendBool :: [Bool] -> [Bool] -> [Bool]
appendInt :: [Int] -> [Int] -> [Int]
-- with generic types/in a polymorphic form
append :: [a] -> [a] -> [a]
append = undefined
-- Reverse a list
-- ==============
reverse' :: [a] -> [a]
reverse' = undefined
-- Delete an element in a list
-- ===========================
-- Note that not every type a is comparable.
-- If elements are not comparable, they cannot be compared meaning that this
-- function cannot work in all cases.
-- delete :: a -> [a] -> [a]
-- To fix this, we can add a type class that requires a to have the equality
-- operator implemented.
delete :: Eq a => a -> [a] -> [a]
delete x xs = undefined
-- Sort a list
-- ===========
-- We run into the same problem as delete in sort.
-- In sort, we have to be able to order elements, ie. to be able to use
-- inequality operators. For this, we can use the Ord (order) type class to
-- represent everything that has the notion of ordering inherent to it.
sort' :: Ord a => [a] -> [a]
sort' = undefined
-- Add the elements within a list
-- ==============================
-- Here, we need every type to be some sort of numerical thing.
-- So we do that with Num!
sum' :: Num a => [a] -> a
sum' = undefined
-- Print things to stdout
-- ======================
-- Here, we need everything that can have a string representation, which is
-- specified with the Show type class.
show :: Show a => a
show = undefined
-- Removing the first/last elements from a list
-- ============================================
-- TODO: Exercise and notes from https://git.cs.bham.ac.uk/fp/fp-learning-2023/-/blob/main/files/LectureNotes/Sections/functions.md#composing-functions
-- Conditionals
-- ============
-- Haskell provides if _ then _ else _, which is typed as Bool -> a -> a -> a.
abs' :: Integer -> Integer
abs' n :: if n >= 0 then n else -n
-- That said, you can also use guards to do the same thing.
abs'' :: Integer -> Integer
abs'' n | n >= 0 = n
| otherwise = -n
-- TODO: Exercise from https://git.cs.bham.ac.uk/fp/fp-learning-2023/-/blob/main/files/LectureNotes/Sections/functions.md#guarded-equations