From b36b2ffda71b06c565b9911800d47f5b0c67cf8a Mon Sep 17 00:00:00 2001 From: Iqbal Ansari Date: Mon, 15 Aug 2016 14:44:28 +0530 Subject: [PATCH] Teach MAL to read and print vectors --- common_lisp/printer.lisp | 16 ++++++++++------ common_lisp/reader.lisp | 12 +++++++----- common_lisp/types.lisp | 1 + 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/common_lisp/printer.lisp b/common_lisp/printer.lisp index fbda2f44..ec2ffa69 100644 --- a/common_lisp/printer.lisp +++ b/common_lisp/printer.lisp @@ -6,6 +6,14 @@ (in-package :printer) +(defun pr-mal-sequence (start-delimiter sequence end-delimiter) + (concatenate 'string + start-delimiter + (format nil + "~{~A~^ ~}" + (mapcar #'pr-str (types::mal-value sequence))) + end-delimiter)) + (defun pr-str (ast) (when ast (case (types::mal-type ast) @@ -14,9 +22,5 @@ ('nil "nil") ('string (format nil "~s" (types::mal-value ast))) ('symbol (format nil "~a" (types::mal-value ast))) - ('list (concatenate 'string - "(" - (format nil - "~{~A~^ ~}" - (mapcar #'pr-str (types::mal-value ast))) - ")"))))) + ('list (pr-mal-sequence "(" ast ")")) + ('vector (pr-mal-sequence "[" ast "]"))))) diff --git a/common_lisp/reader.lisp b/common_lisp/reader.lisp index 45789315..03285cd6 100644 --- a/common_lisp/reader.lisp +++ b/common_lisp/reader.lisp @@ -80,22 +80,24 @@ (let ((token (peek reader))) (cond ((null token) nil) - ((string= token "(") (read-list reader)) + ((string= token "(") (make-mal-list (read-mal-sequence reader))) + ((string= token "[") (make-mal-vector (read-mal-sequence reader "]"))) (t (read-atom reader))))) -(defun read-list (reader) +(defun read-mal-sequence (reader &optional (delimiter ")")) ;; Consume the open brace (consume reader) (let (forms) (loop for token = (peek reader) while (cond - ((null token) (error 'eof :text "EOF encountered while reading list")) - ((string= token ")") (return)) + ((null token) (error 'eof :text (format "EOF encountered while reading list, expected ~a" + delimiter))) + ((string= token delimiter) (return)) (t (push (read-form reader) forms)))) ;; Consume the closing brace (consume reader) - (make-mal-list (nreverse forms)))) + (nreverse forms))) (defun read-atom (reader) (let ((token (next reader))) diff --git a/common_lisp/types.lisp b/common_lisp/types.lisp index 7148a3ed..fd3253e2 100644 --- a/common_lisp/types.lisp +++ b/common_lisp/types.lisp @@ -29,6 +29,7 @@ (export ',constructor)))) (define-mal-type list) +(define-mal-type vector) (define-mal-type number) (define-mal-type symbol) (define-mal-type string)