summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Sima <ben@bsima.me>2018-08-08 19:04:01 -0700
committerBen Sima <ben@bsima.me>2018-08-08 19:04:01 -0700
commit00ca368c2c6864fd059e3ad655afd279b5e75748 (patch)
tree5255316c4a056c1ba08a4286ebfeb4b7fa0cdd77
parentb75fae17e1f887ddb7950410844ac2a819b7cca7 (diff)
Add exercise from this morning
-rwxr-xr-xfpco.hs23
1 files changed, 23 insertions, 0 deletions
diff --git a/fpco.hs b/fpco.hs
new file mode 100755
index 0000000..22ff391
--- /dev/null
+++ b/fpco.hs
@@ -0,0 +1,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])