Created
August 13, 2013 14:32
-
-
Save pooya-raz/6221672 to your computer and use it in GitHub Desktop.
An example of parsing a simple sexp in instaparse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns parse.core | |
(:require [instaparse.core :as insta])) | |
(def parser | |
(insta/parser | |
"sexp = lparen operation rparen | |
<lparen> = <'('> | |
<rparen> = <')'> | |
operation = operator + args | |
operator = '+' | |
args = snumber+ ssexp* | |
<ssexp> = space sexp | |
<snumber> = space number | |
<space> = <#'[ ]*'> | |
number = #'[0-9]+' | |
")) | |
(defn choose-op [op] | |
(case op | |
"+" +)) | |
(def transform-options | |
{:number read-string | |
:args vector | |
:operator choose-op | |
:operation apply | |
:sexp identity | |
}) | |
(defn lisp [input] | |
(->> (parser input) (insta/transform transform-options))) | |
(lisp "(+ 1 2 (+ 3 4))") ;; => 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anyone can tell me why we put a "+" in line9? Thanks.