簡體   English   中英

Haskell 也許加法器沒有 Arguments

[英]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 -> fbf ~ Maybe和映射 function (+1)的特殊情況。 事實上, MaybeFunctor實例被實現為 [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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM