我想要一個類似于 的鏡頭函式%~,但需要一個f回傳 a的函式Maybe,并Just通過fiff回傳 a回傳帶有更新值的a Just,并回傳 a Nothingiff回傳 a Nothing。
下面是一個例子:
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens (makeLenses, (%~), (&), (.~), (^.))
newtype Foo =
Foo
{ _bar :: Int
}
deriving (Show)
makeLenses ''Foo
updateFoo :: Foo -> Maybe Foo
updateFoo f = fmap (\x -> f & bar .~ x) $ doubleIfOdd $ f ^. bar
doubleIfOdd :: Int -> Maybe Int
doubleIfOdd x
| odd x = Just $ x * 2
| otherwise = Nothing
*Main> updateFoo (Foo 3)
Just (Foo {_bar = 6})
*Main> updateFoo (Foo 4)
Nothing
有沒有辦法縮短updateFoo?
updateFoo f = f & bar <someLensFunction> doubleIfOdd
uj5u.com熱心網友回復:
您正在尋找(%%~).
ghci> (1,2) & _1 %%~ \x -> if odd x then Just (x * 2) else Nothing
Just (2,2)
ghci> (2,2) & _1 %%~ \x -> if odd x then Just (x * 2) else Nothing
Nothing
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/386996.html
標籤:哈斯克尔
上一篇:Haskell中IORef的行為
