I have a function that is supposed to return the 2nd last element of a list. Function will return Nothing if nothing can be returned.
data Maybe a = Nothing | Just a secondLast :: [a] -> Maybe a secondLast [] = Nothing secondLast [a, _] = a secondLast (_:xs) = secondLast xs However on compiling i receive this error
* Occurs check: cannot construct the infinite type: a ~ Maybe a * In the expression: a In an equation for `secondLast': secondLast [a, _] = a * Relevant bindings include a :: a (bound at <interactive>:92:13) secondLast :: [a] -> Maybe a (bound at <interactive>:92:1) What am i doing wrong here?
secondLast [x, _] = xreturns ana, not aMaybe a.'a'? What's the type ofJust 'a'?'a'is a Maybe data type, can be represented withNothingora. When we usea, we are returning aNothing | Just avalue. However, Haskell expects an explicitJust aif the only thing that can be returned is anatype?aisn't equivalent typeMaybe a. They are different types. FunctionsecondLasttake a list of values of typeaand return a value of typeMaybe a, so you can't return value of typeainstead. But you know that valuesNothingandJust awhereais value of typeahave typeMaybe awhereais type. Only way to return valueaof typeafrom function is constructing a value of typeMaybe athrough calling type constructionJustwith the value you want return (in this case it isa)atoJust a, so the function always returns a value of typeMaybe a.