如何在 Haskell 中减去 Maybe 值?例如,如果我想减去 Just 8 - Just 5 得到 Just 3,我该怎么做?

Kau*_*Kau 1 monads haskell maybe

我怎样才能做到以下几点。例如,如果我想减去Just 8-Just 5得到Just 3,我该怎么做?

Just 8 - Just 5 = Just 3

Just 15 - Just 9 = Just 6
Run Code Online (Sandbox Code Playgroud)

che*_*ner 6

liftA2函数(从 导入Control.Applicative)将一个普通函数“提升”到一个Applicative上下文中。liftA2 (-)例如,是一个函数,它不接受两个Num a => a值,而是两个(Applicative f, Num a) => f a值,并在相同的上下文中产生结果。这不仅适用于Maybe

>>> liftA2 (-) (Just 8) (Just 5)
Just 3
Run Code Online (Sandbox Code Playgroud)

但对于列表

>>> liftA2 (-) [4,5,6] [1,2,3] -- difference of every pair with one number from each list
[3,2,1,4,3,2,5,4,3]    
Run Code Online (Sandbox Code Playgroud)

Either

>>> liftA2 (-) (Right 8) (Right 5)
Right 3
Run Code Online (Sandbox Code Playgroud)

职能

>>> liftA2 (-) (+3) (*2) 9 -- (\x -> (x + 3) - (x * 2)) 9 == 12 - 18
-6
Run Code Online (Sandbox Code Playgroud)

等等。