[英]Haskell Maybe adder without Arguments
我想知道是否可以編寫 Function
add :: Maybe Int -> Maybe Int
add Just x = Just (x+1)
add Nothing = Nothing
沒有x
。 如同
f = Just.(+1)
然而
add Just = Just.(+1)
引發錯誤: Equations for 'add' have different numbers of arguments
。 有人可以解釋一下為什么這不起作用嗎?
您需要在某處進行模式匹配 - 如果不這樣做,就無法“獲取價值”。 您可以使用一些不安全的 function,例如fromJust
,但是
執行此操作的“適當模塊化”方法是將這個通用模式編寫為高階 function,以便您可以重用它:
Nothing
情況下,您返回Nothing
Just
的情況下,您返回Just
的一些 function應用於 arg 里面綜合以上兩點,我們得出以下結論
maybeMap :: (a -> b) -> Maybe a -> Maybe b
maybeMap _ Nothing = Nothing
maybeMap f (Just x) = Just (f x)
您現在可以使用它來編寫您想要的 function:
add :: Maybe Int -> Maybe Int
add x = maybeMap (+1) x
-- or we can eta reduce it - taking an argument and calling a function with it is the same as just returning the function directly
add = maybeMap (+1)
這個 function 傳統上稱為 map,因為您將“容器內的值”映射到其他東西。
這是您經常需要為不同的“容器”(以及其他一些類型的東西)做的事情,所以我們在標准庫( base
)中有一個類型 class ,以一些理論事物命名:
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Maybe where
fmap = maybeMap
此外,您看到的錯誤完全是另一回事。 在 Haskell 中,在編寫 function 定義時,您的不同情況不允許取不同數量的 arguments:
-- not allowed, since in the first case you've taken two args,
-- but in the second you've only taken one.
bla :: Integer -> Integer -> Integer
bla 0 y = 42
bla x = id
-- this is fine, in both cases we have two arguments
bla :: Integer -> Integer -> Integer
bla 0 y = 42
bla x y = y
第一個參數是Maybe Int
,因此僅指定Just
數據構造函數是不夠的:此數據構造函數有一個參數x
。 因此,您應該使用(Just x)
、 (Just _)
或Just {}
來匹配最后兩個忽略包裝在Just
數據構造函數中的值的位置。 但在這種情況下,您因此無法訪問該值。
但是,您的 function 是fmap:: Functor f => (a -> b) -> fa -> fb
與f ~ Maybe
和映射 function (+1)
的特殊情況。 事實上, Maybe
的Functor
實例被實現為 [src] :
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (fa)
因此,您可以add
實現為:
add :: Maybe Int -> Maybe Int
add = fmap (1+)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.