Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline in Scheme (Racket)

It is possible to have a new line when you write with "display" like

(display "exa \n mple")

But the problem is that there is no any code to have a new line in strings? Like:

"exa \n mple" 

Expected ->

exa
 mple

What I have:

exa \n mple

I couldn't find any information in racket-documentation or anywhere else.

like image 652
Asqan Avatar asked Mar 15 '13 03:03

Asqan


People also ask

How do I print a new line in scheme?

~n or ~% prints a newline character (which is equivalent to \n in a literal format string)

What is a string in Scheme?

A string is a mutable sequence of characters. In the current implementation of MIT Scheme, the elements of a string must all satisfy the predicate char-ascii? ; if someone ports MIT Scheme to a non-ASCII operating system this requirement will change.


2 Answers

For those that came here looking for how to do something similar to Java's println or Python's print that adds a newline at the end of the line, racket has a function called displayln that does just that. More complicated C-like format printing can be done in Racket with fprintf, where it looks like a '~n' gets interpreted as a newline.

Many of Racket's printing functions are documented here: https://docs.racket-lang.org/reference/Writing.html

like image 174
jr15 Avatar answered Oct 01 '22 20:10

jr15


If you need a way to add a newline between strings, then this will work:

(define s (string-append "exa " "\n" " mple"))
s
=> "exa \n mple"

(display s)
=> exa
    mple

In the above snippet, I'm using string-append for sticking together two strings with a newline in the middle. The resulting string s will have a newline in-between when you use it, for example by displaying it.

Obviously it will show up as "exa \n mple", you can't expect the string to jump from one line to the other unless you display it, print it, show it, write it, etc.

like image 24
Óscar López Avatar answered Oct 01 '22 19:10

Óscar López