S-expressions: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Adjusted type of parser. Added Val -> Tree for diagramming.)
(→‎{{header|Haskell}}: Additional output, expression serialized from parse tree.)
Line 3,036: Line 3,036:
import Data.List.Split (splitOn)
import Data.List.Split (splitOn)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
import Data.Tree (Forest, Tree (..), drawForest)
import Data.Tree (Forest, Tree (..), drawForest, foldTree)


------------------------ DATA TYPE -----------------------
------------------------ DATA TYPE -----------------------
Line 3,046: Line 3,046:
| List [Val]
| List [Val]
deriving (Eq, Show, Read)
deriving (Eq, Show, Read)

instance Semigroup Val where
instance Semigroup Val where
List a <> List b = List (a <> b)
List a <> List b = List (a <> b)
Line 3,061: Line 3,061:
" (data (!@# (4.5) \"(more\" \"data)\")))"
" (data (!@# (4.5) \"(more\" \"data)\")))"
]
]
putStrLn $ drawVal $ fst (parseExpr (tokenized expr))
parse = fst (parseExpr (tokenized expr))

putStrLn $ treeDiagram $ forestFromVal parse
putStrLn "Serialized from the parse tree:\n"
putStrLn $ litVal parse


------------------- S-EXPRESSION PARSER ------------------
------------------- S-EXPRESSION PARSER ------------------
Line 3,118: Line 3,122:
----------------------- DIAGRAMMING ----------------------
----------------------- DIAGRAMMING ----------------------


drawVal :: Val -> String
treeDiagram :: Forest Val -> String
drawVal v = drawForest $ fmap (fmap show) (forestFromVal v)
treeDiagram = drawForest . fmap (fmap show)


forestFromVal :: Val -> Forest Val
forestFromVal :: Val -> Forest Val
Line 3,128: Line 3,132:
Node (Symbol "List") (treeFromVal <$> xs)
Node (Symbol "List") (treeFromVal <$> xs)
treeFromVal v = Node v []
treeFromVal v = Node v []

------------------------ FORMATTING ----------------------

ppExpr trees = unwords (go <$> trees)
where
go (Node v xs) = "OK"

litVal (Symbol x) = x
litVal (Int x) = show x
litVal (Float x) = show x
litVal (String x) = '"' : x <> "\""
litVal (List [List xs]) = litVal (List xs)
litVal (List xs) = "(" <> unwords (litVal <$> xs) <> ")"


------------------------- GENERIC ------------------------
------------------------- GENERIC ------------------------
Line 3,161: Line 3,178:
+- String "(more"
+- String "(more"
|
|
`- String "data)"</pre>
`- String "data)"


Serialized from the parse tree:

((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==