I’m attempting this exercise from the PureScript book:
- (Medium) The following data type represents a binary tree with values at the leaves:
data Tree a = Leaf a | Branch (Tree a) (Tree a)
Derive
Encode
andDecode
instances for this type usingpurescript-foreign-generic
, and verify that encoded values can correctly be decoded in PSCi.
My solution:
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
import Foreign.Generic (class Decode, class Encode, F, decodeJSON, defaultOptions, encodeJSON, genericDecode, genericEncode)
data Tree a = Leaf a | Branch (Tree a) (Tree a)
derive instance genericTree :: Generic (Tree a) _
instance decodeTree :: Decode a => Decode (Tree a) where
decode = genericDecode (defaultOptions { unwrapSingleConstructors = true })
instance encodeTree :: Encode a => Encode (Tree a) where
encode = genericEncode (defaultOptions { unwrapSingleConstructors = true })
instance showTree :: Show a => Show (Tree a) where
show = genericShow
But then calling show
or encodeJSON
triggers what looks like a recursion issue:
> t = Leaf 1
> t
/home/miles/projects/purescript/psbe/exercises/chapter10/.psci_modules/node_modules/Data.Symbol/index.js:
14
var IsSymbol = function (reflectSymbol) {
^
RangeError: Maximum call stack size exceeded
Likely related to this issue:
Is there a working solution to this exercise?