Created
June 30, 2011 10:54
-
-
Save laurentpetit/1056008 to your computer and use it in GitHub Desktop.
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 net.cgrand.parsley.fold | |
(:require [net.cgrand.parsley.util :as u])) | |
+(defn make-leaf [s] | |
+ (memoize | |
+ (fn [view] | |
+ ((:unit view) s)))) | |
+ | |
+(defn make-node [tag children] | |
+ (memoize | |
+ (fn [view] | |
+ ((:sum view) tag (map #(if (string? %) ((:unit view) %) (% view)) children))))) | |
+ | |
(defn- anonymous? [x] (and (map? x) (nil? (:tag x)))) | |
+(defn- as-vector [x] (if (vector? x) x (vec x))) | |
+ | |
(defn nodes-vec [nodes] | |
(case (count nodes) | |
1 (let [[x] nodes] | |
(if (anonymous? x) | |
- (:content x) | |
- nodes)) | |
+ (as-vector (:content x)) | |
+ (as-vector nodes))) | |
(reduce (fn [vecs n] (if (anonymous? n) | |
(into vecs (:content n)) | |
(conj vecs n))) [] nodes))) | |
(defn- children-info [children] | |
@@ -19,19 +31,21 @@ | |
(let [child-count (if (string? child) (count child) (or (:count child) 0))] | |
[(conj combined count-acc) (+ count-acc child-count)])) | |
[[] 0] | |
children)) | |
-(defn make-node [tag children] | |
- (if tag | |
- (let [children (nodes-vec children) | |
- [combined count] (children-info children)] | |
- {:tag tag | |
- :content children | |
- :count count | |
- :content-cumulative-count combined}) | |
- {:tag nil :content (nodes-vec children)})) | |
+(def parse-tree-view | |
+ {:unit identity | |
+ :sum (fn [tag children] | |
+ (if tag | |
+ (let [children (nodes-vec children) | |
+ [combined count] (children-info children)] | |
+ {:tag tag | |
+ :content children | |
+ :count count | |
+ :content-cumulative-count combined}) | |
+ {:tag nil :content (nodes-vec children)}))}) | |
(defn make-unexpected [s] | |
(make-node ::unexpected [s])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment