Haskell: 提升一个镜头的正常功能

Haskell: lift a normal function to a lens

我有一个包含各种东西的 HashMap(值来自 Aeson):

cs :: Hashmap Text Value
cs = fromList [("phone", String "+00"), ("count", Number 1)]

我发现我可以使用 Lenses 轻松提取元素,尤其是 lens-aeson:

import Data.Aeson.Lens
import Data.Lens

phone :: Maybe Text
phone = preview (at "phone" . _Just . _String) cs

这很好用。 但是我怎样才能检索我作为 Int 的计数? 我试过了:

count :: Maybe Int
count = preview (at "count" . _Just . _Number) cs

但是这个returns一个Maybe Scientific。 我发现(在 Data-Scientific 中):

toBoundedInteger :: forall i. (Integral i, Bounded i) => Scientific -> Maybe i 

如何在上面的“预览”中提升 toBoundedInteger 以用作透镜(或棱镜)?

使用folding:

count :: Maybe Int
count = preview (at "count" . _Just . _Number . folding boundedInteger) cs

还有 to 但它给了你一个额外的 Maybe 层,你必须用 join:

折叠
count :: Maybe Int
count = preview (at "count" . _Just . _Number . to boundedInteger . to join) cs