How to elegantly represent finite Haskell recursive datastructure in Python?

170 Views Asked by At

Let's have some finite recursive datastructure in Haskell. Eg.

data Tree = Node Tree Tree | Nil

I need to be able to load such datastructure from Haskell to Python, change it and return it back to Haskell.

Is there some standard/elegant way how to do it without much pain? Eg. using some directory like objects?

1

There are 1 best solutions below

0
leftaroundabout On BEST ANSWER

The easiest option is probably to go via JSON, because Haskell has easy support for saving data as JSON and Python can directly load it as dicts.

{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics

import Data.Aeson
import Data.Aeson.TH

data Tree = Node Tree Tree | Nil
 deriving (Generic, FromJSON, ToJSON)

This generates rather awkward JSON though, like, Node (Node Nil Nil) Nil becomes

        "tag": "Node",
        "contents": [
            {
                "tag": "Node",
                "contents": [
                    {
                        "tag": "Nil"
                    },
                    {
                        "tag": "Nil"
                    }
                ]
            },
            {
                "tag": "Nil"
            }
        ]

It gets much more compact with

data TreeNode = Node { lSubtree, rSubtree :: Tree }
 deriving (Generic, FromJSON, ToJSON)

type Tree = Maybe TreeNode

where the equivalent Node (Just (Node Nothing Nothing)) Nothing is now saved as

        {
            "rSubtree": null,
            "lSubtree": {
                "rSubtree": null,
                "lSubtree": null
            }
        }