summaryrefslogtreecommitdiff
path: root/Utility
diff options
context:
space:
mode:
authorGravatar Joey Hess <joey@kitenet.net>2011-12-15 16:59:18 -0400
committerGravatar Joey Hess <joey@kitenet.net>2011-12-15 16:59:18 -0400
commit817b1936e6dac3831721e8f07400181d87f365ca (patch)
treec076db613a4085662a762f5201677247596b68f2 /Utility
parent0f9859ae51324ceb21471a09b423715d9fec7f23 (diff)
add beginning, end
Safe versions of init and last
Diffstat (limited to 'Utility')
-rw-r--r--Utility/BadPrelude.hs36
1 files changed, 29 insertions, 7 deletions
diff --git a/Utility/BadPrelude.hs b/Utility/BadPrelude.hs
index 8e4105cee..49837b927 100644
--- a/Utility/BadPrelude.hs
+++ b/Utility/BadPrelude.hs
@@ -7,22 +7,44 @@
module Utility.BadPrelude where
-{- head is a partial function; head [] is an error -}
+{- read should be avoided, as it throws an error -}
+read :: Read a => String -> a
+read = Prelude.read
+
+{- head is a partial function; head [] is an error
+ - Instead, use: take 1 -}
head :: [a] -> a
head = Prelude.head
-{- tail is also partial -}
+{- tail is also partial
+ - Instead, use: drop 1 -}
tail :: [a] -> [a]
tail = Prelude.tail
-{- init too -}
+{- init too
+ - Instead, use: beginning -}
init :: [a] -> [a]
init = Prelude.init
-{- last too -}
+{- last too
+ - Instead, use: end -}
last :: [a] -> a
last = Prelude.last
-{- read should be avoided, as it throws an error -}
-read :: Read a => String -> a
-read = Prelude.read
+{- All but the last element of a list.
+ - (Like init, but no error on an empty list.) -}
+beginning :: [a] -> [a]
+beginning [] = []
+beginning (x:xs) = beginning' x xs
+ where
+ beginning' _ [] = []
+ beginning' y (z:zs) = y : beginning' z zs
+
+{- Like last, but no error on an empty list. -}
+end :: [a] -> [a]
+end [] = []
+end (x:xs) = end' x xs
+ where
+ end' y [] = [y]
+ end' _ (y:ys) = end' y ys
+