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> |
<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 |
go = until finished parseToken . ([],) |
||
finished (_, []) = True |
finished (_, []) = True |
||
Line 3,082: | Line 3,083: | ||
atom [] = List [] |
atom [] = List [] |
||
atom s@('"' : _) = |
atom s@('"' : _) = |
||
fromMaybe |
fromMaybe |
||
(List []) |
|||
(maybeRead ("String " <> s)) |
|||
atom s = |
atom s = |
||
headDef ( |
headDef (Symbol s) $ |
||
catMaybes $ |
catMaybes $ |
||
maybeRead |
maybeRead |
||
<$> |
<$> fmap (<> (' ' : s)) ["Int", "Float"] |
||
<> ["Symbol \"" <> s <> "\""] |
|||
) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
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 |
| otherwise = c : spacedBrackets cs |
||
------------------------- GENERIC ------------------------ |
|||
⚫ | |||
⚫ | |||
⚫ | |||
{{Out}} |
{{Out}} |
||
<pre>Symbol "List" |
<pre>Symbol "List" |