summaryrefslogtreecommitdiff
path: root/fpco.hs
blob: 22ff39188a4f19adeddd7816281048174d8fdddc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#! /usr/bin/env nix-shell
#! nix-shell -p haskellPackages.ghc -i runghc

{-# OPTIONS_GHC -Wall #-}

{- Problem: write a function that removes the largest value in the list.
 -
 - My first solution used 'Data.List.maximum' and 'Data.List.delete', which
 - solved the problem but was also inefficient because it would consume the
 - entire list at most twice. After talking over the problem, Snoyman showed me
 - a more efficient solution that, due to Haskell's lazy eval, only holds one
 - element of the list at a time: 
 - -}

deleteLargestValue :: [Integer] -> [Integer]
deleteLargestValue [] = []
deleteLargestValue (x:xs) = loop x xs
    where loop _ [] = []
          loop a (b:cs) = if a > b then b:(loop a cs) else a:(loop b cs)

main :: IO ()
main = do
    putStrLn $ "Expect [1,2]: " ++ (show $ deleteLargestValue [1, 2, 3])