Fsharpplus: How to compose Map._item prism?

Created on 3 Sep 2020  路  2Comments  路  Source: fsprojects/FSharpPlus

I want to update a specific item in a map if it exists, similar to what you'd do with items << filtered in a list or similar.

I have tried using Map._item, which AFAIK is a prism, but I can't get it to compose because of a type mismatch between Child and Child option:

```f#
open FSharpPlus
open FSharpPlus.Lens

type Child =
{ Value: int }

type Parent =
{ Children: Map }

let inline _value f (c: Child) =
f c.Value <&> fun v -> { c with Value = v }

let inline _children f (p: Parent) =
f p.Children <&> fun v -> { p with Children = v }

let setChildValue childKey value parent : Parent =
parent |> setl (_children << Map._item childKey << _value) value
// ^^^^^^ Type mismatch

![image](https://user-images.githubusercontent.com/7766733/92100203-c790d580-eddb-11ea-966d-66360e3ebf87.png)


Is there a simple way to achieve what I want?

For comparison, here is a working example that does the same with a list of children with IDs:

```f#
open FSharpPlus
open FSharpPlus.Lens


type Child =
  { Id: string
    Value: int }

type Parent =
  { Children: Child list }


let inline _value f (c: Child) =
  f c.Value <&> fun v -> { c with Value = v }

let inline _children f (p: Parent) =
  f p.Children <&> fun v -> { p with Children = v }

let setChildValue childId value parent : Parent =
  parent |> setl (_children << items << filtered (fun x -> x.Id = childId) << _value) value

Most helpful comment

I recommend the "lens over tea" series for advanced stuff.

Be aware that some stuff from there might break here due to the weaker type system. Specially with traversals.

All 2 comments

Oh, I got it, it's subtly demonstrated here. I was just missing _Some:

f# let setChildValue childKey value parent : Parent = parent |> setl (_children << Map._item childKey << _Some << _value) value

I still have a lot to learn about prisms. The documentation shows the syntax, but doesn't really explain. For example, I'm confused about what _Some actually does (what the "traversal" is and how it impacts optics).

I recommend the "lens over tea" series for advanced stuff.

Be aware that some stuff from there might break here due to the weaker type system. Specially with traversals.

Was this page helpful?
0 / 5 - 0 ratings