S-expressions: Difference between revisions

m
Line 3,030:
 
Or, parsing by hand (rather than with a parser combinator library) and printing a parse tree diagram:
<lang haskell>import{-# Data.BifunctorLANGUAGE (bimap)TupleSections #-}
 
import Data.Bifunctor (bimap)
import Data.List.Split (splitOn)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
Line 3,036 ⟶ 3,038:
 
------------------------ DATA TYPE -----------------------
 
data Val
= Int Integer
Line 3,063 ⟶ 3,064:
parseExpr = go
where
go tokens = until finished parseToken . ([], tokens)
 
finished (_, []) = True
Line 3,082 ⟶ 3,083:
atom [] = List []
atom s@('"' : _) =
fromMaybe (List []) (maybeRead ("String " <> s))
(List [])
(maybeRead ("String " <> s))
atom s =
headDef (ListSymbol []s) $
catMaybes $
maybeRead
<$> ( fmap (<> (' ' : s)) ["Int", "Float"]
<> ["Symbol \"" <> s <> "\""]
)
 
headDef :: a -> [a] -> a
headDef d [] = d
headDef _ (x : _) = x
 
maybeRead :: String -> Maybe Val
Line 3,119 ⟶ 3,116:
spacedBrackets (c : cs)
| c `elem` "()" = ' ' : c : " " <> spacedBrackets cs
| otherwise = c : spacedBrackets cs</lang>
 
------------------------- GENERIC ------------------------
 
headDef :: a -> [a] -> a
headDef d [] = d
headDef _ (x : _) = x</lang>
{{Out}}
<pre>Symbol "List"
9,655

edits