S-expressions: Difference between revisions

Content added Content deleted
Line 3,030: Line 3,030:


Or, parsing by hand (rather than with a parser combinator library) and printing a parse tree diagram:
Or, parsing by hand (rather than with a parser combinator library) and printing a parse tree diagram:
<lang haskell>import Data.Bifunctor (bimap)
<lang haskell>{-# LANGUAGE TupleSections #-}

import Data.Bifunctor (bimap)
import Data.List.Split (splitOn)
import Data.List.Split (splitOn)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
Line 3,036: Line 3,038:


------------------------ DATA TYPE -----------------------
------------------------ DATA TYPE -----------------------

data Val
data Val
= Int Integer
= Int Integer
Line 3,063: Line 3,064:
parseExpr = go
parseExpr = go
where
where
go tokens = until finished parseToken ([], tokens)
go = until finished parseToken . ([],)


finished (_, []) = True
finished (_, []) = True
Line 3,082: Line 3,083:
atom [] = List []
atom [] = List []
atom s@('"' : _) =
atom s@('"' : _) =
fromMaybe (List []) (maybeRead ("String " <> s))
fromMaybe
(List [])
(maybeRead ("String " <> s))
atom s =
atom s =
headDef (List []) $
headDef (Symbol s) $
catMaybes $
catMaybes $
maybeRead
maybeRead
<$> ( fmap (<> (' ' : s)) ["Int", "Float"]
<$> fmap (<> (' ' : s)) ["Int", "Float"]
<> ["Symbol \"" <> s <> "\""]
)

headDef :: a -> [a] -> a
headDef d [] = d
headDef _ (x : _) = x


maybeRead :: String -> Maybe Val
maybeRead :: String -> Maybe Val
Line 3,119: Line 3,116:
spacedBrackets (c : cs)
spacedBrackets (c : cs)
| c `elem` "()" = ' ' : c : " " <> spacedBrackets cs
| c `elem` "()" = ' ' : c : " " <> spacedBrackets cs
| otherwise = c : spacedBrackets cs</lang>
| otherwise = c : spacedBrackets cs

------------------------- GENERIC ------------------------

headDef :: a -> [a] -> a
headDef d [] = d
headDef _ (x : _) = x</lang>
{{Out}}
{{Out}}
<pre>Symbol "List"
<pre>Symbol "List"