strange result with map and apply

Started by fdb, April 26, 2014, 02:57:34 PM

Previous topic - Next topic

fdb


> (map (apply +) '((0 1 2) (3 4 5)))
((0 1 2) (3 4 5))
> (map (fn(x) (apply + x)) '((0 1 2) (3 4 5)))
(3 12)


Why doesn't the first example work?

bairui

#1
With:


(map (apply max) '((0 1 2) (3 4 5)))

we see the expected error:



ERR: missing argument in function max



I don't know why we don't see this with the + function, but the solution to both cases is to use curry:


(map (curry apply +) '((0 1 2) (3 4 5)))

Lutz

#2
Like in Scneme (+) or (apply +) evaluates to 0. So your map expression maps 0 onto two lists.

Using a number as operator is implicit resting. 0 gives you back the whole list.

Try also (map (apply *) '((0 1 2) (3 4 5))) to prove the point. Like in Scheme (*) gives 1.



So using  curry for what you want is the right thing.

bairui

#3
Ah, that makes sense. Thanks, Lutz.

fdb

#4
Thanks a lot bairui and Luts! Hadn't used curry before.



Another question i just encountered is how to change all items in a list in one go, for example:



(set-ref-all "2" '(("1" "2" "3") ("4")) (int $it))
(("1" 2 "3") ("4"))


Works but i want to change all the strings to integers in one go but couldn't find an expression which matches

all the strings, see below some examples i tried but didn't work

> (set-ref-all '((*)) '(("1" "2" "3") ("4")) (int $it))
nil
> (set-ref-all '(?) '(("1" "2" "3") ("4")) (int $it))
nil
> (set-ref-all '(*) '(("1" "2" "3") ("4")) (int $it))
nil
> (set-ref-all '(+) '(("1" "2" "3") ("4")) (int $it))
nil
> (set-ref-all ? '(("1" "2" "3") ("4")) (int $it))
nil
> (set-ref-all * '(("1" "2" "3") ("4")) (int $it))
nil


cormullion

#5
How about:


(set-ref-all '(*) '(("1" "2" "3") ("4")) (map int $it) match)
;-> ((1 2 3) (4))


I admit that match is the one area in newLISP that I always fail to get right in the first few attempts... :)

bairui

#6
Not as veratile as cormullion's match solution, but works for the given example:


(map (curry map int) '(("1" "2" "3") ("4")))

fdb

#7
Thx!



I understood the function from bairui directly (why didn't i think of that..) but i had to look in the documentation to understand cormullion's solution and then i saw in the documentation this example:

(set-ref-all '(oranges *) data (list (first $it) (apply + (rest $it))) match)   ....



Great docs, just have to read them more carefully next time.