Personal tools

99 questions/Solutions/1

From HaskellWiki

< 99 questions | Solutions(Difference between revisions)
Jump to: navigation, search
m (Added another answer: myLast''''')
(3 intermediate revisions by 3 users not shown)
Line 8: Line 8:
 
myLast' = foldr1 (const id)
 
myLast' = foldr1 (const id)
   
myLast'' = head . reverse
+
-- 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)
   
myLast''' xs = xs !! (length xs - 1)
 
 
</haskell>
 
</haskell>
   

Revision as of 15:16, 18 September 2012

(*) Find the last element of a list.

myLast :: [a] -> a
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
.