简体   繁体   中英

Haskell Maybe Int to Int

I have a function where n needs to be an Int but is a Maybe Int ; how could I convert this? I'm aware that this has been asked before, but I don't understand the answer.

where n = case elemIndex column header of
        Nothing -> Nothing
        Just n  -> n

You can use fromMaybe from Data.Maybe , but you have to supply a default value that will be used in case the value is Nothing :

*Q46363709> :m +Data.Maybe
*Q46363709 Data.Maybe> fromMaybe 0 (Just 42)
42
*Q46363709 Data.Maybe> fromMaybe 0 Nothing
0

The Maybe type, however, is a Functor , so often, instead of always supplying default values, you can fmap the result of calling your function. Assuming that your function foo has the type Int -> String , you can do this:

*Q46363709> fmap foo $ Just 42
Just "42"

Often, while you may not have a good default value for the input (ie no good default Int ), you may have a suitable default value for the output. In this case, assuming that "" (the empty String ) is a good default output value, you could use fromMaybe on the output instead of the input:

*Q46363709 Data.Maybe> fromMaybe "" $ fmap foo $ Just 42
"42"
*Q46363709 Data.Maybe> fromMaybe "" $ fmap foo $ Nothing
""

As you can see, when the input is Just 42 , the output is "42" , but when the input is Nothing , then the output is "" .

(BTW, I used show for foo , as you can tell...)

This can't work: On the right side of the -> you have one time a Nothing and the next time an Int . For this to work, you need to provide a default value in case of Nothing (eg -1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM