Home > Enterprise >  Haskell || Missing Null Element
Haskell || Missing Null Element

Time:12-29

I need to create a function that takes the first element of a String but because I am using this function recursively in an other function I need to declare an Edge Case for an Empty List. How can this function do nothing if its given an empty list.

takeFirstElem :: String -> Char
takeFirstElem [] = {- missing Element -}
takeFirstElem (x:xs) = x

What I am missing is something similar to a null element (Like the nil element in an empty List [] ). Does something like this exist or is there an other way to solve this problem?

CodePudding user response:

There is a NULL character \NUL [wiki], but you can not return "nothing". You are supposed to return always a Char per type signature.

Often if the input can be invalid, a Maybe Char is returned and it thus returns a Nothing in case the input is invalid, and a Just x here in case the input is valid, so you can implement this as:

takeFirstElem :: String -> Maybe Char
takeFirstElem [] = Nothing
takeFirstElem (x:_) = Just x

in that case, your takeFirstElem is a special case of listToMaybe :: [a] -> Maybe a.

  • Related