From 817b1936e6dac3831721e8f07400181d87f365ca Mon Sep 17 00:00:00 2001 From: Joey Hess Date: Thu, 15 Dec 2011 16:59:18 -0400 Subject: add beginning, end Safe versions of init and last --- Utility/BadPrelude.hs | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) (limited to 'Utility') 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 + -- cgit v1.2.3