I've been browsing for solutions for an hour now but I just can't figure this out!
If a function has Maybe
as its output, how would I make a construction similar to if-else
in imperative programming?
I am trying to use elemIndex
. If the item is present in the list, I want to do A (with the item). If the item is not present, I want to do B. What's the simplest way to accomplish this?
-- Search for the number 10 in a list of integers and return the information as a string
testFunction :: [Int] -> String
testFunction numbers = elemIndex 10 numbers
-- If 10 is present, return "Index is " show index
-- If 10 is not present, return "Not present"
In most of my attempts I'll run into an error such as:
Couldn't match type `Maybe Int' with `Int'
(I know it's something with Just
and Nothing
- I just can't find or figure out the syntax.)
CodePudding user response:
How about using a case expression (see section 4.3) to pattern match?
testFunction :: [Int] -> String
testFunction numbers = case elemIndex 10 numbers of
Just idx -> "Index is " show idx
Nothing -> "Not present"