Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between range(2,5) and range(2;5)

Template

range(2;5)

producing:

2
3
4

isn't that interesting, as this is explained by manual. However for imperative-style programmer is only matter of time, when he will mistakenly separate parameters by comma (actually I misread the manual, so this was my first attempt), and try template:

range(2, 5)

producing surprising:

0
1
0
1
2
3
4

What is that? How is it defined/explained?

like image 889
Martin Mucha Avatar asked Jul 26 '26 07:07

Martin Mucha


1 Answers

The "comma" operator (as in 2,5) produces a stream. So 2,5 emits two integers, which is why [2,5] evaluates to an array of two integers.

In general, if E/1 has been defined using a form equivalent to def E($x): (i.e., as a "regular" function), then E(a,b) emits the stream E(a) followed by the stream E(b).

And indeed range/1 has been defined as a "regular function".

Non-regular functions

Here's an example of a non-regular function:

# Emit a single JSON object ("bow" is short for "bag of words")
def bow(stream): 
  reduce stream as $word ({}; .[($word|tostring)] += 1);

Notice that the function argument here (stream) is passed to reduce, which of course handles its first argument in a special way.

Since def E($x): is equivalent to def E(x): x as $x, defining bow as

def bow($s): reduce $s as $word ({}; .[($word|tostring)] += 1);

would have completely different (and useless) semantics.

like image 61
peak Avatar answered Jul 29 '26 17:07

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!