-- | Purely functional data structures,
-- First example: reversing a list
-- Functional Programming course 2017.
-- Thomas Hallgren
{-
This started as a skeleton, the definitions were filled in
during the lecture.
-}
--------------------------------------------------------------------------------
import Prelude hiding (sum,reverse)
-- | Computing the sum of a list of numbers
sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x+sum xs
-- | Reversing a list
reverseSlow :: [a] -> [a]
reverseSlow [] = []
reverseSlow (x:xs) = reverseSlow xs ++ [x]
-- | Reverse a list by divide-and-conquer
reverse2 :: [a] -> [a]
reverse2 [] = []
reverse2 [x] = [x]
reverse2 xs = reverse2 xs2 ++ reverse2 xs1
where
(xs1,xs2) = splitAt n xs
n = length xs `div` 2
-- A more efficient way to reverse a list...
reverse :: [a] -> [a]
reverse xs = reverseOnto xs []
reverseOnto :: [a] -> [a] -> [a]
reverseOnto [] rs = rs
reverseOnto (x:xs) rs = reverseOnto xs (x:rs)
{- Below are the tests we ran in GHCi
:load Reverse.hs
:set +s
sum ([1..10000])
sum ([1..100000])
sum ([1..1000000])
sum (reverseSlow [1..10000])
sum (reverseSlow [1..100000])
:r
reverse2 [1..10]
:r
reverse2 [1..10]
sum (reverse2 [1..10000])
sum (reverse2 [1..100000])
sum (reverse2 [1..1000000])
:r
:t reverse
:t reverseOnto
sum (reverse [1..10000])
sum (reverse [1..100000])
sum (reverse [1..1000000])
-}