5

I just read the tutorial at https://www.fpcomplete.com/user/tel/lens-aeson-traversals-prisms, and I have successfully written a query into a json bytestring. However, I am not getting the kind of result value I want.

I'd like to do something along the lines of

if (j^? key "some key" == Just "Google") then ...
                                         else ...

But (j^? key "some key") has the type "Maybe Value".

This must be a common enough pattern that I'd be surprised if there wasn't a utility function to turn a Value into a Text. Any ideas?

nomen
  • 3,626
  • 2
  • 23
  • 40

2 Answers2

3

My lens-fu is pretty limited, but looks like you need _String method of AsPrimitive:

if (j^? key "some key" >>= (^? _String)) == Just "Google"

Or you can convert the right part to Value:

if (j^? key "some key" == Just (String "Google"))
Yuras
  • 13,856
  • 1
  • 45
  • 58
  • `(_String.j ^? key "some key" == Just "Google")` should do the job. Unfortunately, I can't test for stupid mistakes right here. – Carl Sep 15 '13 at 22:22
  • @Carl no, it doesn't, `j` is a `Value`, so `_String.j` doesn't make sense. I don't see the idea, so I don't know how to fix it. – Yuras Sep 15 '13 at 22:34
  • 1
    Oh. Hah. Yes, stupid mistakes. The idea is that prisms compose, so you should be able to compose the `key "foo"` prism with the `_String` prism. But the order should actually be `key "foo" . _String`, I think. – Carl Sep 15 '13 at 22:39
  • Yeah, `(j ^? key "some key" . _String)` works. I finally got enough installed to test. – Carl Sep 15 '13 at 22:46
  • 1
    yes, it works now, thanks. PS the type of `key "foo" . _String` is terrible: `(Applicative f, Indexable Text p, AsValue t) => p Text (f Text) -> t -> f t` :) – Yuras Sep 15 '13 at 22:50
  • That terrible type just means `AsValue t => IndexedTraversal' t Text`. It's quite hard to translate lensey types, but you do get the hang of it. [Here](https://github.com/ekmett/lens/wiki/Synonyms-by-Constraints) is a partial chart—though it doesn't include indexing. – J. Abrahamson Sep 16 '13 at 02:31
3

There is! The _String Prism has type Prism' Value Text, i.e. it attempts to traverse down the branch of Value containing a Text. So you can do j ^? key "some key" . _String == Just "Google".

J. Abrahamson
  • 72,246
  • 9
  • 135
  • 180