2

Trying to replace an element in the map but not sure how to get it done. Not sure what to do to access the key or the value.

Tried the below code but it complains that key or value is not recognized.

let map : Map Text OneElement = M.fromList (("0001", OneElement "one" 1 )::("0002", OneElement "two" 2 )::("0003", OneElement "three" 3 )::("0004", OneElement "four" 4 ):: [])
let result = fmap(\i -> if i.key=="0001" then (OneElement "somethingelse" 1111) else i.value) map  

Also how to access key/value in TextMap.

Anyone can help? Thanks.

barbsan
  • 3,418
  • 11
  • 21
  • 28
Frankie
  • 113
  • 5

1 Answers1

3

The implementation of fmap for DA.Next.Map.Map maps values only, not key, value pairs: fmap : (v -> w) -> Map k v -> Map k w. You could do a find and replace on values as follows:

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = fmap (\i -> if i == OneElement "one" 1 then OneElement "somethingelse" 1111 else i) mymap

Note that I've renamed your map to mymap, as map overlaps with the standard library function map: (a -> b) -> [a] -> [b].

If you wanted to get your hands on key value pairs in a map-like function, you could write your own map function:

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mapEntries : MapKey k => ((k, v) -> w) -> Map k v -> Map k w
mapEntries f = M.fromList . map (\e -> (e._1, f e)) . M.toList

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = mapEntries (\(k, v) -> if k == "0001" then OneElement "somethingelse" 1111 else v) mymap

However, it looks like all you want to do is to replace the element at key "0001". For that, you have the insert function in DA.Next.Map.

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = insert "0001" (OneElement "somethingelse" 1111) mymap
cocreature
  • 801
  • 5
  • 5