lisp,racket,grammar,bnf , How to express BNF using Lisp?

How to express BNF using Lisp?


Tag: lisp,racket,grammar,bnf

I want to express a grammar rule that is written in BNF using Lisp. here is the rule. It is important to note that non-terminals are represented in capital letters and the terminals are represented in small letters:

A -> a A b

I tried to use the define function of lisp to define that grammar. However when I use a define function Lisp obliges me to specify the body of the function that I defined.

   #lang racket
   (define (A a A b B)())

However if I fill the body with whatever like:

   #lang racket
   (define (A a A b B)("Hello World"))

I don't get any error.

My question here is whether I should specify something in the body that will help me define other rules of the grammar, for example should I specify in the body of A the rule for the non terminal B? If that define () function is not the right one to use, what other function(s) would help me represent that BNF grammar using Lisp?


Perhaps I'm misunderstanding something here, but it seems to me that you want to represent an EBNF as a piece of data. If this is the case, you could simply use an s-expression.

Something like this, perhaps?

#lang racket

(define my-ebnf
  `((A (a A b))
    (Q (z z Q z))
    (T (A p Q))))


Backquote String Interpolation

Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

How to use a parameter in a macro call?

I have defined the following simple macro: (defmacro define-class (class-name) `(defclass ,class-name ()())) And now I want to use it in the following function: (defun create-data (mode) (define-class mode)) After compiling the last function I get the following message, the variable MODE is defined but never used. And when I...

racket - algorithm to cut din Ax

I´m developing a mini-game where I need to find out how many lines I can paint in a DIN-A0 paper if I get a DIN-Ax as input . For example: ;car horizontal and cdr vertical lines (define A1 (list 0 1)) (define A2 (list 1 1)) (define A3 (list 1...

abstracting away match in racket

I have a couple of functions that matches for structs that look like such: (define (get-bounding-y struct-lst) (flatten (for/list ([i struct-lst]) (match i [(line _ _ _ _ _ y1 _ y2) (list y1 y2)] [(arc _ _ _ _ _ y radius _ _ _ _ _ _ _...

How to configure the Racket interpreter to support command history?

I've just set up Racket and have been trying out the interpreter. However, I can't seem to go up and down the command history using the arrows (or Ctrlp/Ctrln for that matter) or use Ctrlr to search through it. Is that even supported? Can I build it with that feature...

What's the function to render scribble string with the environment in a hash table?

I'm new to using scribble, but I can't work out how to use its syntax in my own programs, rather than using a scribble language. > (define ht (make-hash '(("Name" . "Simon")))) > (define template "Hello @Name") > (function-i-dont-know ht template) "Hello Simon" What is the function that I'm looking...

Value from binding in LFE interpreter using Erlang

I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

how to change the value of sp-navigate-reindent-after-up in smartparens

I want to change the default behavior of smartparens to remove the whitespace before the close delimiter. I mean, when I type ) after (a b c |, I hope the final result is (a b c)|. Here, the | is cursor. I searched the documentation of smartparens, and find...

display executing name of the current running script

I have tried a few methods, one of them being: (define (program) (find-system-path 'pref-file)) I have read from the documentation (after attempting the above code) and have noticed it is not what i'd need to use, obviously :) Any ideas? Would also like to save this information to a variables....

Invalid specialized parameter in method lambda list

I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

dr racket code error beginning student language

I am writing a function that consumes two images and produces true if the first is larger than the second here is my code (require 2htdp/image) (check-expect(image1 30 40)false) (check-expect(image1 50 20)true) (define(image1 x y) (begin ( circle x "solid" "blue") (circle y "solid" "blue") (if(> x y) "true" "false")))...

How would I make this Racket code DRYer?

I'm porting a Python script to Racket as a learning experience, and I have this function: (define (check-status) (define git [find-executable-path "git"]) (define-values (ckot out in err) (subprocess #f #f #f git "checkout" "-q" "master")) (define-values (local lout lin lerr) (subprocess #f #f #f git "rev-parse" "@")) (define-values (remote rout...

Racket/Scheme embed list within existing list

I'm attempting to embed a list in to an existing list, the problem is explained below. list1 bla bla bla bla list2 useful stuff is here while my function iterates list1 it picks a random point where it will then insert: useful stuff is here the issue is that list2...

Common Lisp - Giving &rest Lists as Arguments

As a result of musings around an exercism problem, I am trying to write a function that takes an input number and an arbitrary length list of divisors to test, along with the expected divisibility (i.e. remainder 0) as a boolean, returning true if all expectations are met (defaulting to...

Are Lisp lists always implemented as linked lists under the hood?

Are Lisp lists always implemented as linked lists under the hood? Is this a problem as far as processor caching goes? If so, are there solutions that use more contiguous structures which help caching?...

Understanding “let” expression in LISP

I am extremely new to lisp, had previous experience with functional programming (Haskell, SML). Why is this code returning 14, and not 10 (ie. 1 + 2y + 3 + 1)? (defvar x 1) (defun g (z) (+ x z)) (defun f (y) (+ (g 1) (let ((x (+ y...

Racket lexer - return list of cons

I'm new to Racket but super excited about it. I've been working on writing a simple lexer for WWW-Authenticate headers. I'm feeling pretty good about the lexing, but now I'd like to change my output. #lang racket (require parser-tools/lex) (require (prefix-in : parser-tools/lex-sre)) (define in (open-input-string "MsRtcOAuth href=\"\",grant_type=\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\", Bearer trusted_issuers=\"\",...

Racket\Scheme compare and delete unwanted items in a list

I have 2 lists: (Define list1 '("xx1" "xx2" xx3" "xx4" "xx5")) (Define list2 '("xx2" "xx4" "xx5")) the items in the list above are just an example, but either way it will be a string item. What I need to do is compare both lists and remove the items in list1...

Exceed evaluation depth when forward function in Emacs Lisp

Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

Racket: Graphing a parabola with elements from a list

I have created the following expression which I would like to graph parabolas based on the last two elements in a list. It looks like this: #lang racket (require plot) (define list-sqr-graph (lambda (lst) (cond [(null? lst) (plot (function sqr 0 0))] [(<= (car lst) 0) (list-sqr-graph (cdr lst))] [(not...

Return items of a list in Lisp

I have to write a program in Lisp that returns the first item of a list if it contains an even number of elements, and the last if it contains an odd number of elements. I need a little advice on where to start? I don't need whole program.

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

EVAL/APPLY: too many arguments given to F

Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

lisp remove a the content of one list from another list

I have a list of string like this called F: ("hello word i'am walid" "goodbye madame") => this list contain two elements of string and I have another list call S like this ("word" "madame") => this contain two words now I want to remove the elements of the list...

How to create a list of sublists in Lisp without map?

I'm trying to make a function that creates a list of all sublists in the given list. What I mean is, when I've got a list: (4 (a g b) g (1 2 3) g (4 5 6)) I want a list: ((a g b) (1 2 3) (4 5...

Find empy lines in text file

I've been learning racket for a few days and I'm puzzled with this task, I'm trying to find empty lines in a text file and select a random empty line to INSERT the text "calculation here", this is as far as I have gotten so far. for example: myfile.txt has...

how to write lex file for input like “{\”a\“:1,\”b\“:2}”

I want to implement a json parser, but having problem with parse object like "{\"a\":1,\"b\":2}", currently the parser output somthing like this '(json (object "{" (kvpair "\"a\":1,\"b\"" ":" (json (number "2"))) "}")) but what i actually want is '(json (object "{" (kvpair "\"a\"" ":" (json (number "1"))) "," (kvpair "\"b\""...

Printing ith row jth column value in lisp

I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made...

Racket - How to use foldr to evaluate if any element in a list satisfies an argument?

I have the task of writing a program called any? that requires an input of a list and one-argument procedure and then tells you if any element in that list satisfies the procedure. ex: (any? odd? (list 2 4 6 8)) -> false I need to use foldr in the...

Char Comparison in Common Lisp

How can i compare characters with Common Lisp? I have google it and found out that there are some functions to do the comparison, like char=, char/=, char<, char>, char<=, and char>=. But, i can't use all of the functions just like: (char= 'a 'a) (char< 'a 'b) If i...

How to use FFI:def-call-in in clisp

I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

Racket not closing TCP port

I've written a simple HTTP echo server in Racket. When I run the server from within DrRacket and then click the Stop button, my program terminates, but the port that was being used takes an annoyingly long time to close. If I run lsof -i :<port> in my terminal after...

Modify list and return it inside a function in lisp

(defun testthis (node index newvalue) (set-nth node index newvalue) node ) I would like to modify the nth element of a list in a function and then returns this list to save the modification performed. How can I do a such function in lisp?...

No-argument (and) returns t

Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

How is it possible to filter a list of directories via “directory-exists?”?

I recently discovered a strange behaviour of racket: Whenever I try to filter a list of directories created via directory-list my REPL returns me an empty list, but when I try the same with an quasiquoted list my REPL returns a correctly filtered list. My questions is now: Why it's...

How would I get the min/max of a list using a key

I currently have a list of objects, each containing a certain attribute. I would like to get the element of the list with the min attribute value. Is there a concise way of doing this? The python equivalent would be something like: min(d, key=d.get) Is there a way of getting...

Generating n-grams with foldl in Racket

So I'm fiddling with Racket. Recursively generating n-grams from a list of words was pretty straightforward: (define (n-grams-recursive words n) (if (< (length words) n) '() (cons (take words n) (n-grams-recursive (cdr words) n)))) And the iterative version also pretty straightforward: (define (n-grams words n) (define (iter n-grams remaining-words) (if...

Get element from list of list in lisp

I am a beginner with lisp. I manipulate list of list: ((name1, second) (name2, second2)) The goal of my function is to get the second element of the list that have name as it first node. For example: my list is: ((name1, second1) (name2, second2)) getelement list name1 should return...

LISP: read number from user and commpare with array index

Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare...

How to get only specific elements of list in racket

Input: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73) ("june 101" 55 55) ("june 104" 55 54) ("aug 201" 220 220)) Desired output: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73)) How do I achieve this? I only want the may terms....

Insertion into a list doesn't reflect outside function whereas deletion does?

I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Is there a way to see the body of a lambda in Racket?

Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

If strings are vectors, why are they immutable?

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

How to move a file in Lisp using rename-file

What's the best way to move a file in Lisp in an implementation-independent way? For example I have an image file: (setq oldpath #P"SERVER:PICTURES;TEMP;PHOTO.PNG") and I want to move it out of the TEMP directory into the PICTURES directory. This seems to work: (setq newpath (make-pathname :host (pathname-host oldpath) :directory...

Common Lisp Object System method execution order

I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

Structuring large Lisp applications

I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

require/typed contract in racket fails

I've tried looking at the docs but i can't find an example that i can use for my case. I need to import break from srfi/1. Here's my attempt. The example works in #lang racket. #lang typed/racket (require/typed (only-in srfi/1 break) ;[break (All (T) (-> (-> T Boolean) (Listof T)...

Where can the Raco Pkgs library “table-editor” be downloaded?

I'm attempting to install this library for Racket, which depends on a library called table-editor. Helpfully, there is a comment in the source: ;; raco pkg install table-panel Unfortunately, that package doesn't seem to exist. Google is not returning helpful results. Does anybody know where to find it?...

output variable value to new file

Currently I have the following code: (define (write host code) (with-output-to-file host (lambda () (printf code)))) (let ([myself (find-system-path 'run-file)] [test (substring myself 1 3)]) (printf "~s\n" myself) (write "hello.txt" myself)) I'm trying to write the value of variable "myself". Sorry for being such a noob, I'm not a huge...

Writing a `define-let` macro, with hygiene

I'm trying to write a define-let macro in racket, which "saves" the header of a (let ((var value) ...) ...) , namely just the (var value) ... part, and allows re-using it later on. The code below works as expected: #lang racket ;; define-let allows saving the header part of...