scheme,racket , Dr Racket list function

## Question:

Tag: scheme,racket

Define a procedure `likenate` that takes a list and returns the list with the symbol `'like` inserted between each pair of adjacent elements in the given list.

I feel like this should be really easy, but I keep getting lists of lists so the check-expects aren't working. I've been stuck on this problem for over an hour. I've tried append and list* and some other things, but I can't figure out how to collapse a list of a list into one list or just get the function to work with the check-expects. Any help on this in BSL+ would be so great. Anyway, this is what I have:

``````; likenate : List -> List

(check-expect (likenate (list 'here 'be 'dragons))
(list 'here 'like 'be 'like 'dragons))

(check-expect (likenate (list 'that 'is 'so 'cool))
(list 'that 'like 'is 'like 'so 'like 'cool))

(check-expect (likenate (list 'like 'like))
(list 'like 'like 'like))

(define (likenate list_like)
(cond [(empty? list_like) '()]
[else  (list (first list_like) 'like (likenate (rest list_like)))
]))
``````

Answer:

You're very close, and you're on the right track thinking about `list*`. In fact, replacing `list` with `list*` in your attempt yields this program, which is almost exactly correct:

``````(define (likenate lst)
(cond [(empty? lst) '()]
[else (list* (first lst) 'like (likenate (rest lst)))]))
``````

You can think of `list*` as a shorthand for multiple `cons`es. To put it simply, `(list* a b c)` is equivalent to `(cons a (cons b c))`. This is necessary because the result of `likenate` is a list, so it needs to be the `cdr` element of the cons pair created by prepending the two new elements to this list.

That implementation almost works, with one small problem. It will insert `'like` elements at the end of the list, so you'll end up with lists like this, instead:

``````(list 'here 'like 'be 'like 'dragons 'like)
``````

Just add an extra clause to the `cond` to handle the last element specially, and everything should work properly:

``````(define (likenate lst)
(cond [(empty? lst) '()]
[(empty? (rest lst)) lst]
[else (list* (first lst) 'like (likenate (rest lst)))]))
``````

# Related:

## display executing name of the current running script

racket
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....

## How to use symbols and lists in scheme to process data?

scheme,racket,grammar,bnf
I am a newbie in scheme, and I am in the process of writing a function that checks pairwise disjointess of rules (for the time being is incomplete), I used symbols and lists in order to represent the rues of the grammar. Uppercase symbol is a non-terminal in the grammar,...

## Racket not closing TCP port

racket
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...

## No-argument (and) returns t

clojure,scheme,lisp,common-lisp
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 would I make this Racket code DRYer?

scheme,racket
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...

## Find empy lines in text file

racket
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...

## Defining cons, car and cdr with lambda - how does it work? [duplicate]

lambda,scheme,sicp,r5rs
This question already has an answer here: Use of lambda for cons/car/cdr definition in SICP 2 answers I can't seem to explain how this definition of cons, car and cdr works: (define (p-cons x y) (lambda (proc) (proc x y))) (define (p-car proc) (proc (lambda (p q) p))) (define...

## Racket\Scheme compare and delete unwanted items in a list

scheme,racket
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...

## output variable value to new file

racket
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...

## Using match with user defined types in PL Racket

racket
The following PL code does not work under #lang pl: Edited code according to Alexis Kings answer (define-type BINTREE [Leaf Number] [Node BINTREE BINTREE]) (: retrieve-leaf : BINTREE -> Number) (define (retrieve-leaf btree) (match btree [(Leaf number) number]) What i'd like to achieve is as follows: Receive a BINTREE as...

## Writing a `define-let` macro, with hygiene

macros,racket,define-syntax,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...

## dr racket code error beginning student language

racket
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 to write lex file for input like “{\”a\“:1,\”b\“:2}”

json,parsing,racket,tokenize,lex
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\""...

## Scheme - unpack list's elements into function [duplicate]

scheme
This question already has an answer here: How do I pass a list as a list of arguments in racket? 2 answers I have a function which takes an unlimited number of args such as (define (func . args)). Say I have a list '(1 2 3), how do...

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

scheme,racket
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...

## Append string to existing textfile in IronScheme

file,scheme,append,r6rs,ironscheme
We are trying to construct a log file using IronScheme, and we have written a code for it using racket. It works fine in racket, but IronScheme throws an error. This is what we have so far: (define write-to-log (lambda(whatToWrite) (with-output-to-file "robot-log.txt" (lambda () (printf (string-append whatToWrite "\r\n" ))) #:exists...

## Accessing call stack depth in Scheme

functional-programming,scheme,tail-recursion,callstack
In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

## Scheme define-macro and/or define-syntax

macros,polymorphism,scheme,overloading
I want to create an overloaded Scheme macro for a simple form of polymorphism. That is, a macro smart enough to expand differently when given params of different types, so that (look-up key container) does the "right" thing for different kinds of containers. (define-macro (look-up key container) (cond ((table? container)...

## Scheme nested lambda function

function,lambda,nested,scheme,sicp
I am a beginner in Scheme. I found this question in MIT exam 1 for SICP lecture. What's the value and type for – ((lambda (a) (lambda (b) (+ (sqrt a) (sqrt b)))) 5) I am having a hard time understanding how this function works. I am really confused about...

## Racket/Scheme embed list within existing list

racket
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...

## Create lists from lists

scheme,racket
I want to write a function which for n arguments will create n lists and each contains n-th element for every argument, for example: (aux '(1 2) '(3 4)) = `((1 3) (2 4)) I wrote such a function: (define (aux . args) (if (null? args) '() (cons (map car...

## abstracting away match in racket

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 _ _ _ _ _ _ _...

## racket - algorithm to cut din Ax

algorithm,racket
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...

## Racket lexer - return list of cons

parsing,racket
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=\"https://foo.com/WebTicket/oauthtoken\",grant_type=\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\", Bearer trusted_issuers=\"\",...

## Any history background about the “yin-yang puzzle” in detail?

scheme,continuations
There are quite a few questions about the "yin-yang puzzle" already in Stackoverflow: How does the yin yang puzzle work? (I assume this is the first one) Haskell (this is my question) C# 5.0 Typed languages ... (there could be something I didn't find yet) I was wondering when and...

## require/typed contract in racket fails

scheme,racket,typed-racket
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?

racket,packages
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?...

## Implement yield and send in Scheme

scheme,coroutine,continuations,guile,delimited-continuations
I'm trying to port yield and yield from from Python to Scheme. Here is an implementation I've done: (define (coroutine routine) (let ((current routine) (status 'new)) (lambda* (#:optional value) (let ((continuation-and-value (call/cc (lambda (return) (let ((returner (lambda (value) (call/cc (lambda (next) (return (cons next value))))))) (if (equal? status 'new) (begin...

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

lambda,scheme,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...

## How to configure the Racket interpreter to support command history?

racket,readline,input-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...

## Returning an element and then deleting the element from a list in Scheme

scheme
I have a list in Scheme which contains numbers. I wrote a function that takes as input one number and a list of objects and checks if the confidence value of the object matches the number. Once I get the object whose confidence values matches the given number, I want...

## “Mapping” Little Schemer to coderbyte challenge: Capitalize

javascript,arrays,recursion,scheme,the-little-schemer
After studying most of The Little Schemer, I've been trying my hand at some recursive solutions to Coderbyte challenges. After some fiddling I threw in cons and thought my upperConsIt would work to look through an array, find all of the instances of a particular letter and capitalize each. Ultimately,...

## Writing a While Loop in Scheme

loops,recursion,lambda,scheme,r5rs
I am trying to implement a while loop using recursion with lambda, but I just don't understand how to do it. I am supposed to start with this lambda expression: ((lambda (x) (x x)) (lambda (x) (x x)) My first question is why does this cause 'eternal' recursion? I try...

## How to get only specific elements of list in racket

functional-programming,scheme,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....

## Racket: Graphing a parabola with elements from a list

list,function,plot,racket
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...

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

racket,scribble
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...

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

recursion,racket,fold
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...

## Translate Scheme closure-defining function into Haskell

haskell,recursion,types,scheme,closures
The following procedure, written in Scheme, (define (eat xs) (lambda (x) (if (eq? x 'vomit) (reverse xs) (eat (cons x xs))))) can be called in the following way: > eat #{procedure 9165 eat} > (eat '()) #{procedure 9166 (unnamed in eat)} > ((eat '()) 1) #{procedure 9166 (unnamed in eat)}...

## Generating n-grams with foldl in Racket

scheme,racket,fold
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...

## Using MIT/GNU Scheme

scheme,edwin
I have downloaded the MIT/GNU Scheme implementation of LISP in order to understand Structure and Interpretation of Computer Programs. However, I am a bit confused about what I am dealing with when I launch the program. When the program is launched, I get two windows: the "MIT/GNU Scheme" window, and...

## Scheme several actions if an if-statement proves true

if-statement,syntax,scheme
The way I understand a scheme if-statement is that the first condition is when the if-statement is true, and the second statement is when it is false. What if I want several conditions for when the statement proves true? An example: (if (= a b) (set! ([a 2])) // This...