Correct Arity

Gleam - print 2d array of x,y pairs

Print all x,y pairs

How would you run a function for each x,y pair in rectangle between x1,y1 and x2,y2 in Gleam? Give it a try:


.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

My first guess was a helper fn to make a range of numbers between x1 - x2, and between y1 - y2, then map over those.

But this is wrong! Or wrong ish in the sense that there's a better way. The problem is this first builds up a 2d array of nums, then maps fn run over them, but you don't actually need to create that first indermediate 2d array. You can instead, as you build up each x,y pair, apply fn run to the x,y pair, so you end up with the desired output without the intermediate numbers taking up more memory.

One final int.range gotcha:

from is inclusive, and to is exclusive.

Which might be what you want, or maybe you want upper to be inclusive too, so you'd do something like this

Anyways, I feel like this is all fine, but maybe not as totally easy/trivial as it is in other languages? Maybe I'm just more used to imperative languages than functional languages. For example in python:


x1 = 2
y1 = 7
x2 = 13
y2 = 15

lower_x = min(x1, x2)
upper_x = max(x1, x2) + 1
lower_y = min(y1, y2)
upper_y = max(y1, y2) + 1

nums = []

for x in range(lower_x, upper_x):
    for y in range(lower_y, upper_y):
        nums.append("(" + str(x) + "," + str(y) + ")")

print(nums)

For me this feels easier, like there's less of a need to achieve enlightement en route to printing points in 2d array. I wonder why?

I like map more than fold

Maybe I had that wrong first thought in Gleam because I find map easier to use than fold? Would that sound ridiculous to someone better at functional programming? On some level map and fold are probably equivalent, like you could implement map using fold, idk. I just feel like I grasp Gleam code using map faster than code using fold. Idk if there's real empirical research on this, but if you gave pop quizzes to random people on the street, would more people be able to correctly answer a question about list.map than about list.fold?

For me map is easier than fold because it doesn't have that extra accumulator floating around. Of course there's a good reason why Gleam needs the acc: Gleam is immutable, it wouldn't make sense to have something like the python nums.append. The immutable Gleam version is probably easier to reason about in many cases and for many people, so idk, it depends.

Anyways, I guess I probably always found fold a bit harder than map but never realized it? Also not saying fold is incredibly painful or anything, or that fold is not the right thing in a lot of cases. And maybe one day I'll look back at this and say uh what was I thinking?? Sorry for subjecting you to such rambling!