Difference between revisions of "99 questions/Solutions/2"

From HaskellWiki
Jump to navigation Jump to search
m (Add description to foldl solution.)
(Added if-based solution)
(2 intermediate revisions by 2 users not shown)
Line 14: Line 14:
   
 
myButLast'''' = head . tail . reverse
 
myButLast'''' = head . tail . reverse
</haskell>
 
   
  +
lastbut1 :: Foldable f => f a -> a
We can also use a pair to keep the last two elements processed from the list. We take advantage of lazy evaluation, such that if the list is too small, the initial elements in the pair get evaluated, resulting in an error:
 
 
lastbut1 = fst . foldl (\(a,b) x -> (b,x)) (err1,err2)
<haskell>
 
  +
where
myButLast''''' = snd.(foldl (\(a,b) c -> (c,a)) (e1, e2))
 
where e1 = error "List too small!"
+
err1 = error "lastbut1: Empty list"
e2 = error "List is null!"
+
err2 = error "lastbut1: Singleton"
  +
  +
lastbut1safe :: Foldable f => f a -> Maybe a
  +
lastbut1safe = fst . foldl (\(a,b) x -> (b,Just x)) (Nothing,Nothing)
  +
  +
myButLast''''' [] = error "Empty list"
  +
myButLast''''' [x] = error "Too few elements"
  +
myButLast''''' (x:xs) =
  +
if length xs == 1 then x
  +
else myButLast''''' xs
 
</haskell>
 
</haskell>
   

Revision as of 20:35, 15 November 2015

(*) Find the last but one element of a list.

myButLast :: [a] -> a
myButLast = last . init

myButLast' x = reverse x !! 1

myButLast'' [x,_]  = x
myButLast'' (_:xs) = myButLast'' xs

myButLast''' (x:(_:[])) = x
myButLast''' (_:xs) = myButLast''' xs

myButLast'''' = head . tail . reverse

lastbut1 :: Foldable f => f a -> a
lastbut1 = fst . foldl (\(a,b) x -> (b,x)) (err1,err2)
  where
    err1 = error "lastbut1: Empty list"
    err2 = error "lastbut1: Singleton"

lastbut1safe :: Foldable f => f a -> Maybe a
lastbut1safe = fst . foldl (\(a,b) x -> (b,Just x)) (Nothing,Nothing)

myButLast''''' [] = error "Empty list"
myButLast''''' [x] = error "Too few elements"
myButLast''''' (x:xs) = 
		if length xs == 1 then x
		else myButLast''''' xs