Counting dup

Started by m i c h a e l, July 13, 2009, 08:01:52 PM

Previous topic - Next topic

m i c h a e l

Lutz,



This isn't really a request so much as sharing an idea: What would you think of adding $idx to dup?



Something like this:


> (dup (format "%c" $idx) 10)
("" "01" "02" "03" "04" "05" "06" "07" "08" "t")
> _


Of course, we can do it this way:


> (map (fn (ea) (format "%c" ea)) (sequence 0 9))
("" "01" "02" "03" "04" "05" "06" "07" "08" "t")


Or even:


> (map (curry format "%c") (sequence 0 9))
("" "01" "02" "03" "04" "05" "06" "07" "08" "t")


But neither of these seems as elegant as the dup solution. What do you think?



m i c h a e l

Lutz

#1
for that specific problem your are citing, the shortest solution would be:


(map char (sequence 0 9))

but perhaps you were thinking in general of a method to create lists of strings, where each element is related to the previous in some form or the other.



Unfortunately 'dup' evaluates its second argument only once, then duplicates the result. But we could generalize the 'series' function, which already offers most of what we are looking for:



(series <num-start> <func> <num-count>) as currently in:


(series 1 (fn (x) (* 2 x)) 5) => '(1 2 4 8 16)

to a new syntax pattern where we can start with any expression:



(series <exp-start> <func> <num-count>) as in:


(series "a" (fn (c) (char (inc (char c)))) 5)  ; in future version

=> ("a" "b" "c" "d" "e")


So func could work not only on numbers but on any data-type in <exp-start>. It turns out a very small change in the existing 'series' function makes this possible and you will see this in the next version.



ps: note that 'series' also includes $idx already so you also will be able to do:


(series "00" (fn () (char (+ $idx 1))) 5) ; in future version
=> ("00" "01" "02" "03" "04")


in this case fn() simply ingnores the incoming argument and only looks on $idx

m i c h a e l

#2
That's great, Lutz! series is one of those functions I've overlooked in the past, so now maybe I'll start using it more.



m i c h a e l