aboutsummaryrefslogtreecommitdiff
path: root/p99/p12.neb
diff options
context:
space:
mode:
Diffstat (limited to 'p99/p12.neb')
-rw-r--r--p99/p12.neb37
1 files changed, 37 insertions, 0 deletions
diff --git a/p99/p12.neb b/p99/p12.neb
new file mode 100644
index 0000000..7d8ec4e
--- /dev/null
+++ b/p99/p12.neb
@@ -0,0 +1,37 @@
+; P12 Decode a run-length encoded list.
+; Given a run-length code list generated as specified in problem P11.
+; Construct its uncompressed version.
+
+(def a (list (list 4 "a") "b" (list 2 "c") (list 2 "a") "d" (list 4 "e")))
+
+(func extend (lst1 lst2)
+ (reduce append lst2 lst1))
+
+(func flatten (lst)
+ (reduce
+ (lambda (x y) (extend x y))
+ lst
+ (list)))
+
+(func decode (lst)
+ (flatten
+ (map
+ (lambda (item)
+ (if (eq? 1 (length item))
+ (list item)
+ (rpt (first item) (last item))))
+ lst)))
+
+(func rpt (cnt let)
+ (if (eq? cnt 1)
+ (list let)
+ (extend (list let) (rpt (- cnt 1) let))))
+
+; iterative
+(func rpt-iter (cnt let)
+ (def out (list))
+ (for-count cnt
+ (redef out (append out let)))
+ out)
+
+(print (->string (decode a)))