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)
Advertisements
Categories: Haskell, programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: