2

这是我正在尝试做的事情:

justExpose :: Maybe a -> a
justExpose (Just x) = x
justExpose Nothing = -- an empty object of type a

有任何想法吗?

4

4 回答 4

10

如果您的类型a中有幺半群结构,那么您可以使用它:

import Data.Monoid

justExpose :: Monoid a => Maybe a -> a
justExpose (Just x) = x
justExpose Nothing = mempty

这方面的一些例子:

λ> let x = Nothing :: Maybe (Sum Int)
λ> justExpose x
Sum {getSum = 0}
λ> justExpose (Just [])
[]

但是您应该注意,Maybe类型在很多情况下都非常有用。

于 2014-12-24T21:16:59.037 回答
4

您要求的是许多其他语言中的“null”。Haskell 故意不提供这样的东西,因为它不安全。

可以得到代码编译如下:

justExpose :: Maybe a -> a
justExpose (Just x) = x
justExpose Nothing = undefined

但是如果你用 a 调用它,Nothing你会得到一个运行时异常,因为顾名思义,这个值是未定义的!

更新:正如一些人所指出的,此功能由 提供Data.Maybe.fromJust,您可以通过搜索hoogle来查找您的类型签名Maybe a -> a

于 2014-12-24T21:17:28.753 回答
4

The Maybe a is the standard "type with empty value".

The way to extract that a is to perform a case-split or (better) use a

fromMaybe :: a -> Maybe a -> a  -- Defined in ‘Data.Maybe’

function, which is declared as

fromMaybe :: a -> Maybe a -> a
fromMaybe def optional = 
    case optional of
        Just value -> value
        Nothing    -> def

So, you just need to import Data.Maybe and call fromMaybe with an appropriate "empty object" of your choice (or what the task's domain requires there).

You can also leave it as Maybe a or even start to work in the Maybe monad, if you have many a -> Maybe b actions in the domain; the question here is the reason behind your "How do I...".

于 2014-12-25T10:53:55.890 回答
3
于 2014-12-24T21:21:30.790 回答