Home > Haskell, programming > Haskell snippet

Haskell snippet

Just some snippet of Haskell code today to return the last but one element of a list. The first implementation uses the built-in functions last and take.

-- Return the last but one element of a list.  This implementation uses         
-- last and take.                                                               
penlast :: [a] -> a
penlast xs = if null xs || length xs <= 2
             then head xs
             else last (take ((length xs) - 1) xs)

The second implementation below uses the built-in functions head and drop.

-- Return the penultimate element of a list.  This implementation uses          
-- head and drop.                                                               
penhead :: [a] -> a
penhead xs = if null xs || length xs <= 2
             then head xs
             else head (drop ((length xs) - 2) xs)
Categories: Haskell, programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment