formatting 'nil'

Started by jopython, December 02, 2012, 06:18:05 PM

Previous topic - Next topic

jopython

I want  the formatted output to look like  follows for a csv file

apple,,,peach


But I get an error.

> (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

bairui

#1
There might be a shorter way to express this, but my limited (new)lisp-fu offers you:


(format "%s,%s,%s,%s" (map (fn (x) (or x "")) fruits))

cormullion

#2
That's good, bairui. Similar is:


(format "%s,%s,%s,%s" (replace nil fruits ""))

jopython

#3
Thanks bairui and cormullion.

m i c h a e l

#4
cormullion's solution is considerably faster:


> (time (replace nil fruits "") 1000000)
173.114
> (time (map (fn (x) (or x "")) fruits) 1000000)
3435.875
> _
>


m i c h a e l

cormullion

#5
Hey michael! Your second post this year - glad you still visit!



Yes, mapping anonymous functions is always going to be slower.

m i c h a e l

#6
cormullion,



Yes, I'm still here, lurking in the shadows. I don't do much programming lately, but I'm still an enthusiastic newlisper!

bairui

#7
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.

cormullion

#8
since replace is so useful, you might sometimes want to use it non-destructively:


(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

bairui

#9
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. :-)