Contents

How to use Python like Lisp

Contents

Lisp has some very effective way to get jobs done, this article give you a direct way to use Python like Lisp.``` cons = lambda el, lst: (el, lst)

1
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None) 

car = lambda lst: lst[0] if lst else lst

1
cdr = lambda lst: lst[1] if lst else lst 

nth = lambda n, lst: nth(n-1, cdr(lst)) if n ]]> 0 else car(lst)

1
length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count

begin = lambda *args: args[-1]

1
2
3
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("niln")
```where `w = sys.stdout.write````
foldr = lambda f, i: lambda s: reduce(f, s, i)

foldl = reduce

mapcar = map

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

Pay attention about the speed when you use Python, here is a benchmarks for 5 languages:

 from [The Great Computer Language Shootout](http://www.bagley.org/~doug/shootout/).

Test

Lisp

Java

Python

Perl

C++

hash access

1.06

3.23

4.01

1.85

1.00

exception handling

0.01

0.90

1.54

1.73

1.00

Legend

sum numbers from file

7.54

2.63

8.34

2.49

1.00

\> 100 x C++

reverse lines

1.61

1.22

1.38

1.25

1.00

50-100 x C++

matrix multiplication

3.30

8.90

278.00

226.00

1.00

10-50 x C++

heapsort

1.67

7.00

84.42

75.67

1.00

5-10 x C++

array access

1.75

6.83

141.08

127.25

1.00

2-5 x C++

list processing

0.93

20.47

20.33

11.27

1.00

1-2 x C++

object instantiation

1.32

2.39

49.11

89.21

1.00

< 1 x C++

word count

0.73

4.61

2.57

1.64

1.00

**Median**

1.67

4.61

20.33

11.27

1.00

**25% to 75%**

0.93 to 1.67

2.63 to 7.00

2.57 to 84.42

1.73 to 89.21

1.00 to 1.00

**Range**

0.01 to 7.54

0.90 to 20.47

1.38 to 278

1.25 to 226

1.00 to 1.00

Relative Resource: _[Python for Lisp Programmers](http://norvig.com/python-lisp.html)_    by _[Peter Norvig](http://www.norvig.com/)_