从镜头获取默认值的Maybe

时间:2014-02-28 03:53:13

标签: haskell lens

许多镜头吸气剂返回Maybe值。我经常需要用默认值替换它们。

说地图查找但是默认。

fromMaybe "" $ Map.fromList [(1,"Foo")] ^? at 1

这可以用镜头语法编写吗?也许接近这个:

Map.fromList [(1,"Foo")] ^? at 1.or ""

1 个答案:

答案 0 :(得分:10)

我认为你想要的是

non :: Eq a => a -> Iso a (Maybe a)

non foo基本上是

 case someMaybe of
   Nothing -> foo
   Just a  -> a

在你的情况下

 someMap ^. at 1 . non ""

巧合的是,这正是non docs给出的例子。

如果你想和ix一起使用,那你就不走运了,但是你可以随时做到

 -- Import Data.Monoid
 defaulting :: a -> s -> Getting (First a) s a -> a
 defaulting a s fold = fromMaybe a $ s ^? fold

 foo = defaulting 0 [1, 2, 3] $ ix 3 -- 0