From 817b1936e6dac3831721e8f07400181d87f365ca Mon Sep 17 00:00:00 2001 From: Joey Hess Date: Thu, 15 Dec 2011 16:59:18 -0400 Subject: [PATCH] add beginning, end Safe versions of init and last --- Utility/BadPrelude.hs | 54 ++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 16 deletions(-) diff --git a/Utility/BadPrelude.hs b/Utility/BadPrelude.hs index 8e4105ceea..49837b9273 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 -} -head :: [a] -> a -head = Prelude.head - -{- tail is also partial -} -tail :: [a] -> [a] -tail = Prelude.tail - -{- init too -} -init :: [a] -> [a] -init = Prelude.init - -{- last too -} -last :: [a] -> a -last = Prelude.last - {- 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 + - Instead, use: drop 1 -} +tail :: [a] -> [a] +tail = Prelude.tail + +{- init too + - Instead, use: beginning -} +init :: [a] -> [a] +init = Prelude.init + +{- last too + - Instead, use: end -} +last :: [a] -> a +last = Prelude.last + +{- 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 +