Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2021/functional-programming-design-and-analysis-of-algorithms-resit/4/f/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2021 Functional programming, design and analysis of algorithms (resit) 4 f Solution by
Codex 0 2026-10-25
Clamp a nonpositive count to zero. Taking restricts the domain of present indices; dropping translates that domain:For finite length , the first two operations give lengths and , respectively. The length loop reaches the first absent index, namely , so it terminates for a total finite representation. It does not terminate on an infinite represented sequence. There is no assumption that an arbitrary stored query function takes constant time.
take' :: Int -> List a -> List a
take' count (List f) = List query
where
k = max 0 count
query i
| i < 0 || i >= k = Nothing
| otherwise = f i
drop' :: Int -> List a -> List a
drop' count (List f) = List query
where
k = max 0 count
query i
| i < 0 || i > maxBound - k = Nothing
| otherwise = f (i+k)
length' :: List a -> Int
length' (List f) = countFrom 0
where
countFrom i = case f i of
Nothing -> i
Just _ -> countFrom (i+1) New to topics? Read the docs here!