chris Frisina
chris Frisina

Reputation: 19688

Second most recent list item Haskell

I am trying to get the second item in a list in Haskell. I would assume the best way to do this is to get the head of the tail of a 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 get the following:

Parse error in pattern: head
Possibly caused by a missing 'do'?

Why do I need to do a do or is that a false suggestion?

Upvotes: 3

Views: 233

Answers (3)

Reed Oei
Reed Oei

Reputation: 1508

The easiest way to get the second item is to use the !! infix operator. It lets you access a particular item in a list. Normally, for most lists this would be too slow, but because it is only the second item, it doesn't really matter.

Upvotes: 0

Don Stewart
Don Stewart

Reputation: 137947

I would use pattern matching, as it is clearer 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.

Upvotes: 5

randomusername
randomusername

Reputation: 8097

The shortest way to do that is to just pattern match it.

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

Upvotes: 9

Related Questions