How to keep a type of algebraic type data in constant

For this type of data

data Tree = Node String Tree Tree | Leaf String 

And real data like this

 my_tree = (Node "first node" (Leaf "leaf") (Node "second node" (Leaf "leaf") (Leaf "leaf"))) 

How can I save this in the database using constants, in particular, how to make the "OR" part?

I tried to define the model as follows

 share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Tree value String leftTree Leaf rightTree Leaf deriving Show Leaf value String deriving Show |] 

The recursive structure will be stored in the row column as a json row automatically, which is very nice. But how can we, or can we, define an β€œOR” structure in a constant model?

+8
haskell yesod persistent
source share
1 answer

Persistent can only store ADTs that do not have child data. I.E. You can save the following:

 data Tag = Leaf | Fork 

But recursive structures like this cannot be saved without serializing it in JSON:

 data Tree a = (Leaf a) | Fork (Tree a) (Tree a) 

What you need to understand is that Persistent is a type persistence layer on top of the database, so you need to think about your schema in terms of what is efficiently stored in the database, and not in terms of what is convenient. Haskell Structural Structure .

 share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Tree parent TreeId Maybe value String deriving Show |] 

This diagram will give you the equivalent of the following structure.

 data Tree a = Value a [Tree a] 
+9
source share

All Articles