I’m having trouble figuring out how to return a Map
from JavaScript to PureScript. I assume converting to JSON with argonaut would be a good intermediate step, as described in these FFI tips, but decoding doesn’t work, despite having a representation that looks identical between PS and JS in the logs.
Main.js
"use strict";
exports.mapSetFooJson = m => {
let n = new Map(m);
n.set("Foo", 42);
let s = JSON.stringify(Array.from(n));
console.log("JS JSON: " + s);
return s;
};
Main.purs
foreign import mapSetFooJson :: Json -> Json
mapSetFoo :: Map String Int -> Either String (Map String Int)
mapSetFoo m = decodeJson $ mapSetFooJson $ encodeJson m
myMap :: Map String Int
myMap = fromFoldable [ Tuple "hat" 1, Tuple "cat" 2 ]
main :: Effect Unit
main = do
logShow myMap
log $ "PS JSON: " <> (stringify $ encodeJson myMap)
logShow $ mapSetFoo myMap
Logs
$ spago run
(fromFoldable [(Tuple "cat" 2),(Tuple "hat" 1)])
PS JSON: [["cat",2],["hat",1]]
JS JSON: [["cat",2],["hat",1],["Foo",42]]
(Left "Couldn't decode List: Value is not an Array")
Here’s the project containing the above snippet.