我的功能n
必须是Int
,但是Maybe Int
;我怎么能转换这个?我之前已经知道这个问题,但我不明白答案。
where n = case elemIndex column header of
Nothing -> Nothing
Just n -> n
答案 0 :(得分:5)
您可以使用fromMaybe
中的Data.Maybe
,但您必须提供一个默认值,以便在值为Nothing
时使用:
*Q46363709> :m +Data.Maybe
*Q46363709 Data.Maybe> fromMaybe 0 (Just 42)
42
*Q46363709 Data.Maybe> fromMaybe 0 Nothing
0
Maybe
类型是Functor
,因此通常不是始终提供默认值,而是fmap
调用您的函数的结果。假设您的函数foo
的类型为Int -> String
,则可以执行以下操作:
*Q46363709> fmap foo $ Just 42
Just "42"
通常,虽然您可能没有良好的输入默认值(即没有良好的默认值Int
),但您可能有一个合适的输出默认值。在这种情况下,假设""
(空String
)是一个很好的默认输出值,您可以在输出上使用fromMaybe
而不是输入:
*Q46363709 Data.Maybe> fromMaybe "" $ fmap foo $ Just 42
"42"
*Q46363709 Data.Maybe> fromMaybe "" $ fmap foo $ Nothing
""
如您所见,当输入为Just 42
时,输出为"42"
,但当输入为Nothing
时,输出为""
。
(顺便说一句,我使用show
作为foo
,你可以告诉...)
答案 1 :(得分:1)
这不起作用:在Nothing
的右侧,您有一次Int
,下一次Nothing
。为此,您需要在function remove(array, items) {
array[Symbol.iterator] = function* () {
for (let value of Object.values(this)) {
if (!items.includes(value)) {
yield value;
}
}
};
}
var array = ['cat', 'dog', 'elephant', 'lion', 'tiger', 'mouse'];
remove(array, ['dog', 'lion']);
console.log([...array]);
console.log(array);
(例如-1)