[英]Using Maybe type in Haskell
I'm trying to utilize the Maybe type in Haskell. 我正在尝试利用Haskell中的Maybe类型。 I have a lookup for key, value tuples that returns a Maybe. 我在寻找返回Maybe的键,值元组。 How do I access the data that was wrapped by Maybe? 如何访问Maybe包装的数据? For example I want to add the integer contained by Maybe with another integer. 例如,我想将Maybe包含的整数与另一个整数相加。
Alternatively you can pattern match: 或者,您可以模式匹配:
case maybeValue of
Just value -> ...
Nothing -> ...
You could use Data.Maybe.fromMaybe
, which takes a Maybe a
and a value to use if it is Nothing
. 您可以使用Data.Maybe.fromMaybe
,它使用Maybe a
和一个值(如果为Nothing
来使用。 You could use the unsafe Data.Maybe.fromJust
, which will just crash if the value is Nothing
. 您可以使用不安全的Data.Maybe.fromJust
,如果值为Nothing
,它将崩溃。 You likely want to keep things in Maybe
. 您可能想将事情保留在Maybe
。 If you wanted to add an integer in a Maybe
, you could do something like 如果您想在Maybe
添加一个整数,则可以执行以下操作
f x = (+x) <$> Just 4
which is the same as 这与
f x = fmap (+x) (Just 4)
f 3
will then be Just 7
. f 3
将变为Just 7
。 (You can continue to chain additional computations in this manner.) (您可以继续以这种方式链接其他计算。)
Just as a side note: Since Maybe
is a Monad
, you can build computations using do
-notation ... 附带说明:由于Maybe
是Monad
,您可以使用do
-notation建立计算...
sumOfThree :: Maybe Int
sumOfThree = do
a <- someMaybeNumber
b <- someMaybeNumber
c <- someMaybeNumber
let k = 42 -- Just for fun
return (a + b + c + k)
Examples for "maybe": “也许”的示例:
> maybe 0 (+ 42) Nothing
0
> maybe 0 (+ 42) (Just 12)
54
Many people are against the use of fromJust
, however it can be convenient if you are aware of what will happen when the lookup fails (error!!) 许多人反对使用fromJust
,但是如果您知道查找失败(错误!)时将发生的情况,这可能会很方便。
Firstly you will need this: 首先,您将需要以下内容:
import Data.Maybe
And then your lookup from a list of tuples will look like this 然后您从元组列表中查找将如下所示
Data.Maybe.fromJust $ lookup key listOfTuples
For example, successful lookup: 例如,成功查找:
Data.Maybe.fromJust $ lookup "a" [("a",1),("b",2),("c",3)]
1
And horrible failure looks like this: 可怕的失败看起来像这样:
Data.Maybe.fromJust $ lookup "z" [("a",1),("b",2),("c",3)]
*** Exception: Maybe.fromJust: Nothing
Sorry, I should have googled better. 抱歉,我应该用Google搜索更好。
using the fromMaybe function is exactly what I need. 使用fromMaybe函数正是我需要的。 fromMaybe will return the value in Maybe if it is not nothing, otherwise it will return a default value supplied to fromMaybe. 如果不为空,fromMaybe将返回Maybe中的值,否则它将返回提供给fromMaybe的默认值。
http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Maybe.html http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Maybe.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.