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

From HaskellWiki
Jump to navigation Jump to search
(Copied solution from 99 questions/1 to 10)
 
(Added base case to myLast)
 
(6 intermediate revisions by 5 users not shown)
Line 3: Line 3:
 
<haskell>
 
<haskell>
 
myLast :: [a] -> a
 
myLast :: [a] -> a
  +
myLast [] = error "No end for empty lists!"
 
myLast [x] = x
 
myLast [x] = x
 
myLast (_:xs) = myLast xs
 
myLast (_:xs) = myLast xs
Line 8: Line 9:
 
myLast' = foldr1 (const id)
 
myLast' = foldr1 (const id)
   
  +
-- Prelude> const 1 2
myLast'' = head . reverse
 
  +
-- 1
  +
-- Prelude> (flip const) 1 2
  +
-- 2
  +
myLast'' = foldr1 (flip const)
  +
 
myLast''' = head . reverse
  +
  +
myLast'''' = foldl1 (curry snd)
  +
  +
myLast''''' [] = error "No end for empty lists!"
  +
myLast''''' x = x !! (length x -1)
  +
 
</haskell>
 
</haskell>
   
 
The <hask>Prelude</hask> also provides the function <hask>last</hask>.
 
The <hask>Prelude</hask> also provides the function <hask>last</hask>.
  +
  +
[[Category:Programming exercise spoilers]]

Latest revision as of 13:52, 25 August 2014

(*) Find the last element of a list.

myLast :: [a] -> a
myLast [] = error "No end for empty lists!"
myLast [x] = x
myLast (_:xs) = myLast xs

myLast' = foldr1 (const id)

-- Prelude> const 1 2
-- 1
-- Prelude> (flip const) 1 2
-- 2
myLast'' = foldr1 (flip const)

myLast''' = head . reverse

myLast'''' = foldl1 (curry snd)

myLast''''' [] = error "No end for empty lists!"  
myLast''''' x = x !! (length x -1)

The Prelude also provides the function last.