Home > Enterprise >  How to handle the Maybe output of a function?
How to handle the Maybe output of a function?

Time:10-06

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"

CodePudding user response:

The maybe function encapsulates the pattern-matching on a Maybe a value to handle both Nothing and Just x values. The first argument is a replacement for Nothing; the second is a function that gets applied to the wrapped value in a Just x.

> import Data.Char (toUpper)
> maybe "foo" (map toUpper) Nothing
"foo"
> maybe "foo" (map toUpper) (Just "bar")
"BAR"

For your use case,

testFunction numbers = maybe 
                          "Not present"
                          (\x -> "Index is "    show x)
                          (elemIndex 10 numbers)
-- In point-free form,
-- testFunction = maybe "Not present" (("Index is "   ) . show) . elemIndex 10
  • Related