Skip to content

Loops and Strings

Yesterday I left you with a program that really needed to "YS up"!

$ ys -e '
url =:
  "https://github.com/dominictarr/random-name/raw/master/first-names.json"

people =: url.curl().json/load().shuffle().take(3)
shoes =: read("shoes.yaml").yaml/load()

say: str(people.0, " wears size ", shoes.0.size, " ", join([shoes.0.name, "s"]))
say: str(people.1, " wears size ", shoes.1.size, " ", join([shoes.1.name, "s"]))
say: str(people.2, " wears size ", shoes.2.size, " ", join([shoes.2.name, "s"]))
'

Let's make this awesome!

YS Interpolation🔗

Great interpolation is something I want in every language I program in. I don't always get it, but if I'm going to invent a new language, it's a must.

Interpolation is the ability to expand variables or expressions into a string, in place.

Here's a quick example of both in YS:

# File 'add'
!YS-v0
a b =: ARGS
say: "$a + $b = $(a + b)"

When we run it like this:

$ ys add 16 26
16 + 26 = 42

That's so simple. Both to write and for others to understand.

YS allows interpolation in double quoted strings and also literal strings (the | syntax) when the string is in "code mode". Just use $var or $(expr) to evaluate and expand them in place.

Let's use interpolation in our shoes program.

$ ys -e '
url =:
  "https://github.com/dominictarr/random-name/raw/master/first-names.json"

people =: url.curl().json/load().shuffle().take(3)
shoes =: read("shoes.yaml").yaml/load()

say: "$(people.0) wears size $(shoes.0.size) $(shoes.0.name)s"
say: "$(people.1) wears size $(shoes.1.size) $(shoes.1.name)s"
say: "$(people.2) wears size $(shoes.2.size) $(shoes.2.name)s"
'
Rebecca wears size 10 sneakers
Dian wears size 10 boots
Iolande wears size 8 sandals

Better!

Let's make it better still!

Loops🔗

We could make this better if only YS had loops!

Pffft. We got your looping constructs right here! Several of them!

Let's use the each looping function for this.

$ ys -e '
url =:
  "https://github.com/dominictarr/random-name/raw/master/first-names.json"

people =: url.curl().json/load().shuffle().take(3)
shoes =: read("shoes.yaml").yaml/load()

each i range(people.count()):  # (0, 1, 2)
  person =: people.$i
  shoe =: shoes.$i
  say: "$person wears size $(shoe.size) $(shoe.name)s"
'
Myrtle wears size 10 sneakers
Phillis wears size 10 boots
Evonne wears size 8 sandals

I like it!

Take your shoes off!🔗

By this time I bet you're getting tired of seeing programs about shoes.

Me too. Tomorrow will be different. Promise.

It's Summertime, let's go barefoot!

Comments