简体   繁体   中英

Haskell: lift a normal function to a lens

I have a HashMap that contains various things (Value is from Aeson):

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

I figured out I could extract elements easily with Lenses and in particular lens-aeson :

import Data.Aeson.Lens
import Data.Lens

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

This works well. But How can I retrieve my count as a Int? I tried:

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

But this returns a Maybe Scientific . I found (in Data-Scientific):

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

How to lift toBoundedInteger to work as a Lens (or Prism) in my "preview" above?

Use folding :

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

There is also to but it gives you an extra layer of Maybe that you have to collapse with join :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM