Page 1 of 1
formatting 'nil'
Posted: Mon Dec 03, 2012 2:18 am
by jopython
I want the formatted output to look like follows for a csv file
But I get an error.
Code: Select all
> (setq fruits '("apple" nil nil "peach"))
("apple" nil nil "peach")
> (format "%s,%s,%s,%s" fruits)
ERR: data type and format don't match in function format : nil
How to tell format to deal with an empty data type like nil
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 8:16 am
by bairui
There might be a shorter way to express this, but my limited (new)lisp-fu offers you:
Code: Select all
(format "%s,%s,%s,%s" (map (fn (x) (or x "")) fruits))
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 12:59 pm
by cormullion
That's good, bairui. Similar is:
Code: Select all
(format "%s,%s,%s,%s" (replace nil fruits ""))
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 1:05 pm
by jopython
Thanks bairui and cormullion.
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 5:38 pm
by m i c h a e l
cormullion's solution is considerably faster:
Code: Select all
> (time (replace nil fruits "") 1000000)
173.114
> (time (map (fn (x) (or x "")) fruits) 1000000)
3435.875
> _
>
m i c h a e l
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 5:45 pm
by cormullion
Hey michael! Your second post this year - glad you still visit!
Yes, mapping anonymous functions is always going to be slower.
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 5:53 pm
by m i c h a e l
cormullion,
Yes, I'm still here, lurking in the shadows. I don't do much programming lately, but I'm still an enthusiastic newlisper!
Re: formatting 'nil'
Posted: Mon Dec 03, 2012 9:27 pm
by bairui
W00t! Learned about replace() today. Yay. :-) Thanks, cormullion.
It was interesting to see Michael's speed test. I hadn't thought about how slow map() might be. And what a speed difference!
Another thing to note about the two different solutions, though, is that the map() is non-destructive, whereas replace() alters the original list.
Re: formatting 'nil'
Posted: Tue Dec 04, 2012 9:00 am
by cormullion
since
replace is so useful, you might sometimes want to use it non-destructively:
Code: Select all
(time (replace nil fruits "") 100000)
11.262
(time (replace nil (copy fruits) "") 100000)
63.958
(time (map (lambda (x) (or x "")) fruits) 100000)
167.338
Re: formatting 'nil'
Posted: Tue Dec 04, 2012 12:41 pm
by bairui
I should have thought about copy(). I have to do that all the time in Vim because its map() function is destructive. :-/
Thanks for the reminder, and speed test, Cormullion. Completed this thread nicely, I'd say. :-)