Second most recent element of a Haskell list

I am trying to get the second item in a list in Haskell. I would suggest that the best way to do this is to get the head of the tail of the list.

secondMostRecentChoice :: History -> Choice // a choice is just a Bool like Bake | NoBake
secondMostRecentChoice [] = "Not Enough History"
secondMostRecentChoice history = 
    if ( length history == 1 ) 
        then "Still Not Enough History"
    else if (length history >= 2)
        then (head [b | (head a,b) <- history]) //Here is the problem
        else "Not supposed to be here"
    else "Not supposed to be here"


but I am getting this:

Parsing error in template: head
      Could it be that "do" is missing?

Why do I need to do do

or is this a false suggestion?


source to share

3 answers

I would use pattern matching since it is more clear what the failure modes are:

   second :: [a] -> a
   second []      = error "Empty list"
   second [x]     = error "Singleton list"
   second (_:x:_) = x


Clearer, no? Makes the specification obvious.



The shortest way to do this is to simply match the template to it.

secondElem :: [a] -> Maybe a
secondElem (_:x:_) = Just x
secondElem _       = Nothing




The easiest way to get the second element is using the infix operator !!

. It allows you to access a specific item in a list. This will usually be too slow for most lists, but since this is only the second item it doesn't really matter.



All Articles