我想知道是否可以撰寫函式
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。有人可以解釋一下為什么這不起作用嗎?
uj5u.com熱心網友回復:
您需要在某處進行模式匹配- 不這樣做就無法“獲取價值”。你可以使用一些不安全的函式,比如fromJust,但是
- 這是不安全的 - 做一個案例和模式匹配更好
- 它仍然在其中進行模式匹配,因此您并沒有真正避免這樣做。
執行此操作的“適當模塊化”方法是將此通用模式撰寫為高階函式,以便您可以重用它:
- 在這種
Nothing情況下,你回傳Nothing - 在
Just情況下,回傳Just的一些功能應用到ARG內
綜合以上兩點,我們得出以下結論
maybeMap :: (a -> b) -> Maybe a -> Maybe b
maybeMap _ Nothing = Nothing
maybeMap f (Just x) = Just (f x)
您現在可以使用它來撰寫所需的函式:
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)
此函式傳統上稱為 map,因為您將“容器內的值”映射到其他內容。
這是你經常需要為不同的“容器”(以及一些其他型別的東西)做的事情,所以我們在標準庫 ( base) 中有一個型別類,以一些理論事物命名:
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Maybe where
fmap = maybeMap
此外,您看到的錯誤完全是另一回事。在 Haskell 中,在撰寫函式定義時,您的不同情況不允許采用不同數量的引數:
-- 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
uj5u.com熱心網友回復:
第一個引數是 a Maybe Int,因此僅指定Just資料建構式是不夠的:這個資料建構式有一個引數x。因此(Just x),您應該使用,(Just _)或Just {}匹配最后兩個忽略包裝在Just資料建構式中的值。但在這種情況下,您將無法訪問該值。
但是,您的函式是fmap :: Functor f => (a -> b) -> f a -> f bwithf ~ Maybe和 as 映射函式的特例( 1)。實際上, 的Functor實體Maybe 實作為 [src]:
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a)
因此,您可以實作add為:
add :: Maybe Int -> Maybe Int
add = fmap (1 )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365262.html
上一篇:沒有啟動類的集成測驗和托管ASP.NETCore6.0
下一篇:如何為我自己的型別創建實體?
