-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path97-appendici.lsp
7356 lines (5457 loc) · 324 KB
/
97-appendici.lsp
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
===========
APPENDICI
===========
============================================================================
The fifteen ideas characterizing LISP
============================================================================
The fifteen ideas characterizing LISP:
1. Computing with symbolic expressions rather than numbers.
2. Representation of symbolic expressions and other information by list structure in computer memory.
3. Representation of information on paper, from keyboards and in other external media mostly by multi-level lists and sometimes by S-expressions. It has been important that any kind of data can be represented by a single general type.
4. A small set of selector and constructor operations expressed as func- tions, i.e. car, cdr and cons.
5. Composition of functions as a tool for forming more complex functions.
6. The use of conditional expressions for getting branching into function definitions.
7. The recursive use of conditional expressions as a sufficient tool for building computable functions.
8. The use of lambda-expressions for naming functions.
9. The storage of information on the property lists of atoms.
10. The representation of LISP programs as LISP data that can be manipulated by object programs. This has prevented the separation between system programmers and application programmers. Everyone can "improve" his LISP, and many of these "improvements" have developed into improvements to the language.
11. The conditional expression interpretation of Boolean connectives.
12. The LISP function eval that serves both as a formal definition of the language and as an interpreter.
13. Garbage collection as the means of erasure.
14. Minimal requirements for declarations so that LISP statements can be executed in an on-line environment without preliminaries.
15. LISP statements as a command language in an on-line environment.
============================================================================
Lista delle funzioni newLISP
============================================================================
List processing, flow control, and integer arithmetic
=====================================================
+, -, *, /, % integer arithmetic
++ increment integer numbers
-- decrement integer numbers
<, >, = compares any data type: less, greater, equal
<=, >=, != compares any data type: less-equal, greater-equal, not-equal
: constructs a context symbol and applies it to an object
and logical and
append appends lists ,arrays or strings to form a new list, array or string
apply applies a function or primitive to a list of arguments
args retrieves the argument list of a function or macro expression
assoc searches for keyword associations in a list
begin begins a block of functions
bigint convert a number to big integer format
bind binds variable associations in a list
case branches depending on contents of control variable
catch evaluates an expression, possibly catching errors
chop chops elements from the end of a list
clean cleans elements from a list
collect repeat evaluating an expression and collect results in a list
cond branches conditionally to expressions
cons prepends an element to a list, making a new list
constant defines a constant symbol
count counts elements of one list that occur in another list
curry transforms a function f(x, y) into a function fx(y)
define defines a new function or lambda expression
define-macro defines a macro or lambda-macro expression
def-new copies a symbol to a different context (namespace)
difference returns the difference between two lists
doargs iterates through the arguments of a function
dolist evaluates once for each element in a list
dostring evaluates once for each character in a string
dotimes evaluates once for each number in a range
dotree iterates through the symbols of a context
do-until repeats evaluation of an expression until the condition is met
do-while repeats evaluation of an expression while the condition is true
dup duplicates a list or string a specified number of times
ends-with checks the end of a string or list against a key of the same type
eval evaluates an expression
exists checks for the existence of a condition in a list
expand replaces a symbol in a nested list
explode explodes a list or string
extend extends a list or string
first gets the first element of a list or string
filter filters a list
find searches for an element in a list or string
flat returns the flattened list
fn defines a new function or lambda expression
for evaluates once for each number in a range
for-all checks if all elements in a list meet a condition
if evaluates an expression conditionally
index filters elements from a list and returns their indices
intersect returns the intersection of two lists
lambda defines a new function or lambda expression
last returns the last element of a list or string
length calculates the length of a list or string
let declares and initializes local variables
letex expands local variables into an expression, then evaluates
letn initializes local variables incrementally, like nested lets
list makes a list
local declares local variables
lookup looks up members in an association list
map maps a function over members of a list, collecting the results
match matches patterns against lists; for matching against strings, see find and regex
member finds a member of a list or string
not logical not
nth gets the nth element of a list or string
or logical or
pop deletes and returns an element from a list or string
pop-assoc removes an association from an association list
push inserts a new element into a list or string
quote quotes an expression
ref returns the position of an element inside a nested list
ref-all returns a list of index vectors of elements inside a nested list
rest returns all but the first element of a list or string
replace replaces elements inside a list or string
reverse reverses a list or string
rotate rotates a list or string
select selects and permutes elements from a list or string
self Accesses the target object inside a FOOP method
set sets the binding or contents of a symbol
setf setq sets contents of a symbol or list, array or string reference
set-ref searches for an element in a nested list and replaces it
set-ref-all searches for an element in a nested list and replaces all instances
silent works like begin but suppresses console output of the return value
slice extracts a sublist or substring
sort sorts the members of a list
starts-with checks the beginning of a string or list against a key of the same type
swap swaps two elements inside a list or string
unify unifies two expressions
unique returns a list without duplicates
union returns a unique list of elements found in two or more lists.
unless evaluates an expression conditionally
until repeats evaluation of an expression until the condition is met
when evaluates a block of statements conditionally
while repeats evaluation of an expression while the condition is true
String and conversion functions
===============================
address gets the memory address of a number or string
bigint convert a number to big integer format
bits translates a number into binary representation
char translates between characters and ASCII codes
chop chops off characters from the end of a string
dostring evaluates once for each character in a string
dup duplicates a list or string a specified number of times
ends-with checks the end of a string or list against a key of the same type
encrypt does a one-time–pad encryption and decryption of a string
eval-string compiles, then evaluates a string
explode transforms a string into a list of characters
extend extends a list or string
find searches for an element in a list or string
find-all returns a list of all pattern matches found in string
first gets the first element in a list or string
float translates a string or integer into a floating point number
format formats numbers and strings as in the C language
get-char gets a character from a memory address
get-float gets a double float from a memory address
get-int gets a 32-bit integer from a memory address
get-long gets a long 64-bit integer from a memory address
get-string gets a string from a memory address
int translates a string or float into an integer
join joins a list of strings
last returns the last element of a list or string
lower-case converts a string to lowercase characters
member finds a list or string member
name returns the name of a symbol or its context as a string
nth gets the nth element in a list or string
pack packs newLISP expressions into a binary structure
parse breaks a string into tokens
pop pops from a string
push pushes onto a string
regex performs a Perl-compatible regular expression search
regex-comp pre-compiles a regular expression pattern
replace replaces elements in a list or string
rest gets all but the first element of a list or string
reverse reverses a list or string
rotate rotates a list or string
select selects and permutes elements from a list or string
setf setq sets contents of a string reference
slice extracts a substring or sublist
source returns the source required to bind a symbol as a string
starts-with checks the start of the string or list against a key string or list
string transforms anything into a string
sym translates a string into a symbol
title-case converts the first character of a string to uppercase
trim trims a string on one or both sides
unicode converts ASCII or UTF-8 to UCS-4 Unicode
utf8 converts UCS-4 Unicode to UTF-8
utf8len returns length of an UTF-8 string in UTF-8 characters
unpack unpacks a binary structure into newLISP expressions
upper-case converts a string to uppercase characters
Floating point math and special functions
=========================================
abs returns the absolute value of a number
acos calculates the arc-cosine of a number
acosh calculates the inverse hyperbolic cosine of a number
add adds floating point or integer numbers and returns a floating point number
array creates an array
array-list returns a list conversion from an array
asin calculates the arcsine of a number
asinh calculates the inverse hyperbolic sine of a number
atan calculates the arctangent of a number
atanh calculates the inverse hyperbolic tangent of a number
atan2 computes the principal value of the arctangent of Y / X in radians
beta calculates the beta function
betai calculates the incomplete beta function
binomial calculates the binomial function
ceil rounds up to the next integer
cos calculates the cosine of a number
cosh calculates the hyperbolic cosine of a number
crc32 calculates a 32-bit CRC for a data buffer
dec decrements a number in a variable, list or array
div divides floating point or integer numbers
erf calculates the error function of a number
exp calculates the exponential e of a number
factor factors a number into primes
fft performs a fast Fourier transform (FFT)
floor rounds down to the next integer
flt converts a number to a 32-bit integer representing a float
gammai calculates the incomplete Gamma function
gammaln calculates the log Gamma function
gcd calculates the greatest common divisor of a group of integers
ifft performs an inverse fast Fourier transform (IFFT)
inc increments a number in a variable, list or array
inf? checks if a floating point value is infinite
log calculates the natural or other logarithm of a number
min finds the smallest value in a series of values
max finds the largest value in a series of values
mod calculates the modulo of two numbers
mul multiplies floating point or integer numbers
NaN? checks if a float is NaN (not a number)
round rounds a number
pow calculates x to the power of y
sequence generates a list sequence of numbers
series creates a geometric sequence of numbers
sgn calculates the signum function of a number
sin calculates the sine of a number
sinh calculates the hyperbolic sine of a number
sqrt calculates the square root of a number
ssq calculates the sum of squares of a vector
sub subtracts floating point or integer numbers
tan calculates the tangent of a number
tanh calculates the hyperbolic tangent of a number
uuid returns a UUID (Universal Unique IDentifier)
Matrix functions
================
det returns the determinant of a matrix
invert returns the inversion of a matrix
mat performs scalar operations on matrices
multiply multiplies two matrices
transpose returns the transposition of a matrix
Array functions
===============
append appends arrays
array creates and initializes an array with up to 16 dimensions
array-list converts an array into a list
array? checks if expression is an array
det returns the determinant of a matrix
first returns the first row of an array
invert returns the inversion of a matrix
last returns the last row of an array
mat performs scalar operations on matrices
multiply multiplies two matrices
nth returns an element of an array
rest returns all but the first row of an array
setf sets contents of an array reference
slice returns a slice of an array
transpose transposes a matrix
Bit operators
=============
<<, >> bit shift left, bit shift right
& bitwise and
| bitwise inclusive or
^ bitwise exclusive or
~ bitwise not
Predicates
==========
atom? checks if an expression is an atom
array? checks if an expression is an array
bigint? checks if a number is a big integer
context? checks if an expression is a context
directory? checks if a disk node is a directory
empty? checks if a list or string is empty
even? checks the parity of an integer number
file? checks if a file exists
float? checks if an expression is a float
global? checks if a symbol is global
inf? checks if a floating point value is infinite
integer? checks if an expression is an integer
lambda? checks if an expression is a lambda expression
legal? checks if a string contains a legal symbol
list? checks if an expression is a list
macro? checks if an expression is a lambda-macro expression
NaN? checks if a float is NaN (not a number)
nil? checks if an expression is nil
null? checks if an expression is nil, "", (), 0 or 0.0
number? checks if an expression is a float or an integer
odd? checks the parity of an integer number
protected? checks if a symbol is protected
primitive? checks if an expression is a primitive
quote? checks if an expression is quoted
string? checks if an expression is a string
symbol? checks if an expression is a symbol
true? checks if an expression is not nil
zero? checks if an expression is 0 or 0.0
Date and time functions
=======================
date converts a date-time value to a string
date-list returns a list of year, month, day, hours, minutes, seconds from a time value in seconds
date-parse parses a date string and returns the number of seconds passed since January 1, 1970, (formerly parse-date)
date-value calculates the time in seconds since January 1, 1970 for a date and time
now returns a list of current date-time information
time calculates the time it takes to evaluate an expression in milliseconds
time-of-day calculates the number of milliseconds elapsed since the day started
Statistics, simulation and modeling functions
=============================================
amb randomly selects an argument and evaluates it
bayes-query calculates Bayesian probabilities for a data set
bayes-train counts items in lists for Bayesian or frequency analysis
corr calculates the product-moment correlation coefficient
crit-chi2 calculates the Chi² statistic for a given probability
crit-f calculates the F statistic for a given probability
crit-t calculates the Student's t statistic for a given probability
crit-z calculates the normal distributed Z for a given probability
kmeans-query calculates distances to cluster centroids or other data points
kmeans-train partitions a data set into clusters
normal makes a list of normal distributed floating point numbers
prob-chi2 calculates the tail probability of a Chi² distribution value
prob-f calculates the tail probability of a F distribution value
prob-t calculates the tail probability of a Student's t distribution value
prob-z calculates the cumulated probability of a Z distribution value
rand generates random numbers in a range
random generates a list of evenly distributed floats
randomize shuffles all of the elements in a list
seed seeds the internal random number generator
stats calculates some basic statistics for a data vector
t-test compares means of data samples using the Student's t statistic
Pattern matching
================
ends-with tests if a list or string ends with a pattern
find searches for a pattern in a list or string
find-all finds all occurrences of a pattern in a string
match matches list patterns
parse breaks a string along around patterns
ref returns the position of an element inside a nested list
ref-all returns a list of index vectors of elements inside a nested list
regex finds patterns in a string
replace replaces patterns in a string
search searches for a pattern in a file
starts-with tests if a list or string starts with a pattern
unify performs a logical unification of patterns
Financial math functions
========================
fv returns the future value of an investment
irr calculates the internal rate of return
nper calculates the number of periods for an investment
npv calculates the net present value of an investment
pv calculates the present value of an investment
pmt calculates the payment for a loan
Input/output and file operations
================================
append-file appends data to a file
close closes a file
current-line retrieves contents of last read-line buffer
device sets or inquires about current print device
exec launches another program, then reads from or writes to it
load loads and evaluates a file of newLISP code
open opens a file for reading or writing
peek checks file descriptor for number of bytes ready for reading
print prints to the console or a device
println prints to the console or a device with a line-feed
read reads binary data from a file
read-char reads an 8-bit character from a file
read-file reads a whole file in one operation
read-key reads a keyboard key
read-line reads a line from the console or file
read-utf8 reads UTF-8 character from a file
save saves a workspace, context, or symbol to a file
search searches a file for a string
seek sets or reads a file position
write writes binary data to a file
write-char writes a character to a file
write-file writes a file in one operation
write-line writes a line to the console or a file
Processes and the Cilk API
==========================
! shells out to the operating system
abort aborts a child process started with spawn
destroy destroys a process created with fork or process
exec runs a process, then reads from or writes to it
fork launches a newLISP child process
pipe creates a pipe for interprocess communication
process launches a child process, remapping standard I/O and standard error
receive receive a message from another process
semaphore creates and controls semaphores
send send a message to another process
share shares memory with other processes
spawn launches a child process for Cilk process management
sync waits for child processes launched with spawn and collects results
wait-pid waits for a child process to end
File and directory management
=============================
change-dir changes to a different drive and directory
copy-file copies a file
delete-file deletes a file
directory returns a list of directory entries
file-info gets file size, date, time, and attributes
make-dir makes a new directory
real-path returns the full path of the relative file path
remove-dir removes an empty directory
rename-file renames a file or directory
HTTP networking API
===================
base64-enc encodes a string into BASE64 format
base64-dec decodes a string from BASE64 format
delete-url deletes a file or page from the web
get-url reads a file or page from the web
json-error returns error information from a failed JSON translation.
json-parse parses JSON formatted data
post-url posts info to a URL address
put-url uploads a page to a URL address
xfer-event registers an event handler for HTTP byte transfers
xml-error returns last XML parse error
xml-parse parses an XML document
xml-type-tags shows or modifies XML type tags
Socket TCP/IP, UDP and ICMP network API
=======================================
net-accept accepts a new incoming connection
net-close closes a socket connection
net-connect connects to a remote host
net-error returns the last error
net-eval evaluates expressions on multiple remote newLISP servers
net-interface Sets the default interface IP address on multihomed computers.
net-ipv Switches between IPv4 and IPv6 internet protocol versions.
net-listen listens for connections to a local socket
net-local returns the local IP and port number for a connection
net-lookup returns the name for an IP number
net-packet send a custom configured IP packet over raw sockets
net-peek returns the number of characters ready to be read from a network socket
net-peer returns the remote IP and port for a net connect
net-ping sends a ping packet (ICMP echo request) to one or more addresses
net-receive reads data on a socket connection
net-receive-from reads a UDP on an open connection
net-receive-udp reads a UDP and closes the connection
net-select checks a socket or list of sockets for status
net-send sends data on a socket connection
net-send-to sends a UDP on an open connection
net-send-udp sends a UDP and closes the connection
net-service translates a service name into a port number
net-sessions returns a list of currently open connections
API for newLISP in a web browser
================================
display-html display an HTML page in a web browser
eval-string-js evaluate JavaScript in the current web browser page
Reflection and customization
============================
command-event pre-processes the command-line and HTTP requests
error-event defines an error handler
history returns the call history of a function
last-error report the last error number and text
macro create a reader expansion macro
ostype contains a string describing the OS platform
prefix Returns the context prefix of a symbol
prompt-event customizes the interactive newLISP shell prompt
read-expr reads and translates s-expressions from source
reader-event preprocess expressions before evaluation event-driven
set-locale switches to a different locale
source returns the source required to bind a symbol to a string
sys-error reports OS system error numbers
sys-info gives information about system resources
term returns the term part of a symbol or its context as a string
System functions
================
$ accesses system variables $0 -> $15
callback registers a callback function for an imported library
catch evaluates an expression, catching errors and early returns
context creates or switches to a different namespace
copy copies the result of an evaluation
debug debugs a user-defined function
delete deletes symbols from the symbol table
default returns the contents of a default functor from a context
env gets or sets the operating system's environment
exit exits newLISP, setting the exit value
global makes a symbol accessible outside MAIN
import imports a function from a shared library
main-args gets command-line arguments
new creates a copy of a context
pretty-print changes the pretty-printing characteristics
read-expr translates a string to an s-expression without evaluating it
reset goes to the top level
signal sets a signal handler
sleep suspends processing for specified milliseconds
sym creates a symbol from a string
symbols returns a list of all symbols in the system
throw causes a previous catch to return
throw-error throws a user-defined error
timer starts a one-shot timer, firing an event
trace sets or inquires about trace mode
trace-highlight sets highlighting strings in trace mode
Importing libraries
===================
address returns the memory address of a number or string
callback registers a callback function for an imported library
flt converts a number to a 32-bit integer representing a float
float translates a string or integer into a floating point number
get-char gets a character from a memory address
get-float gets a double float from a memory address
get-int gets a 32-bit integer from a memory address
get-long gets a long 64-bit integer from a memory address
get-string gets a string from a memory address
import imports a function from a shared library
int translates a string or float into an integer
pack packs newLISP expressions into a binary structure
struct Defines a data structure with C types
unpack unpacks a binary structure into newLISP expressions
newLISP internals API
=====================
command-event pre-processes the command-line and HTTP requests
cpymem copies memory between addresses
dump shows memory address and contents of newLISP cells
prompt-event customizes the interactive newLISP shell prompt
read-expr reads and translates s-expressions from source
reader-event preprocess expressions before evaluation event-driven
Riguardare la lista rinfresca la memoria e aiuta a trovare funzioni... prima sconosciute.
============================================================================
Sul linguaggio newLISP - FAQ di Lutz Mueller
============================================================================
Questa è la traduzione della pagina web relativa alle FAQ (Frequently Asked Questions) su newLISP:
http://www.newLISP.org/index.cgi?FAQ
1. Cos'è newLISP e cosa posso fare con questo linguaggio?
2. Perché newLISP, perché non uno degli altri LISP standard?
3. Come posso studiare newLISP?
4. Quanto è veloce newLISP?
5. newLISP ha le matrici?
6. newLISP ha le tabelle hash?
7. newLISP ha una gestione automatica della memoria?
8. newLISP può passare i dati per riferimento?
9. Come funziona il variable scoping in newLISP?
10. newLISP gestisce il multiprocessing?
11. Posso usare newLISP per compiti di calcolo distribuiti?
12. Possiamo utilizzare la metodologia di programmazione orientata agli oggetti?
13. Cosa sono di pacchetti e moduli?
14. Quali sono alcune differenze tra newLISP e altri LISP?
15. newLISP funziona sul sistema operativo XYZ?
16. newLISP può gestire i caratteri speciali del mio paese e della mia lingua?
17. L'indicizzazione implicita non infrange le regole di sintassi del LISP?
18. newLISP può essere incorporato in altri programmi?
19. Posso mettere il copyright ai miei script anche se newLISP è concesso in licenza GPL?
20. Dove posso segnalare eventuali bug?
1. Cos'è newLISP e cosa posso fare con questo linguaggio?
---------------------------------------------------------
newLISP è un linguaggio di scripting simile al LISP per fare quelle cose che si fanno tipicamente con linguaggi di scripting: programmazione per internet, amministrazione di sistema, elaborazione testi, incollare diversi altri programmi insieme, ecc. newLISP è un LISP di scripting per persone che sono affascinate dalla bellezza e dal potere espressivo del LISP, ma che hanno bisogno di una versione ridotta per imparare facilmente l'essenziale.
2. Perché newLISP, perché non uno degli altri LISP standard?
------------------------------------------------------------
LISP è un vecchio linguaggio nato, cresciuto e standardizzato in tempi molto diversi da oggi, tempi in cui la programmazione era per persone altamente istruite che hanno progettato programmi. newLISP è un LISP rinato come linguaggio di scripting: pragmatico e casuale, semplice da imparare senza che tu debba conoscere concetti avanzati di informatica. Come ogni buon linguaggio di scripting, newLISP è relativamente semplice da imparare e potente per terminare il proprio lavoro senza problemi.
Vedi anche: "In Praise of Scripting: Real Programming Pragmatics" di Ronald P. Loui
http://web.cs.mun.ca/~harold/Courses/Old/CS2500.F09/Diary/04563874.pdf
newLISP ha un tempo di avvio molto veloce, ha bisogno di poche risorse come spazio su disco e memoria ed ha una pratica API con funzioni native per networking, statistica, machine learning, espressioni regolari, multiprocessing e calcolo distribuito, non aggiunte successivamente con moduli esterni.
3. Come posso studiare newLISP?
-------------------------------
Almeno all'inizio, studia principalmente newLISP utilizzandolo. Se capisci questo:
(+ 1 2 3); calcola la somma di 1,2,3 => 6
e questo:
(define (double x) (+ x x)); definisce una funzione
(doppio 123); calcola il doppio di 123 => 246
allora hai imparato abbastanza per iniziare a programmare in newLISP. Ci sono alcuni altri concetti come le funzioni anonime, l'applicazione di funzioni, spazi dei nomi (contesti) e l'indicizzazione implicita. Imparerai queste tecniche mentre usi newLISP.
I libri su LISP o Scheme, che sono due standard di LISP diversi e più vecchi, insegnano concetti che non hai la necessità di imparare per programmare in newLISP. Molte volte newLISP esprime le cose in modo diverso dai LISP tradizionali e in modi più applicabili ai compiti di programmazione odierni e ad un livello superiore più vicino al problema in questione.
Impara a risolvere i problemi con il modo newLISP! Per una comprensione più approfondita di newLISP, leggi la sezione del "Manuale utente" di newLISP, con meno teoria e più esempi. Dai uno sguardo al "Manuale di riferimento" per avere un'idea della profondità e dell'ampiezza delle funzioni API integrate.
Per lavorare seriamente con newLISP occorre leggere il manuale "Code Patterns" con altri suggerimenti e pezzi di codice. Un'ottima introduzione per principianti è il libro "Introduction to newLISP" oppure i video tutorial che sono disponibili nella pagina ufficiale della documentazione.
Molte funzioni in newLISP hanno una funzionalità facile da capire, ma sono molto più potenti quando si conoscono e si usano le opzioni speciali di quella funzione. La profondità della API di newLISP non è basata sulla quantità delle funzioni, ma piuttosto sulle opzioni e sulle sintassi multipla di ogni specifica funzione
Inizia a scrivere il tuo primo programma ora. Guarda le porzioni di codice (snippet) riportate in tutto il manuale e su questo sito web. Se hai domande, iscriviti al forum di discussione di newLISP e chiedi.
4. Quanto è veloce newLISP?
---------------------------
La velocità di calcolo di newLISP è confrontabile con quella dei popolari strumenti di scripting come Perl o Python, ma si comporta meglio quando si tratta di tempi di avvio e di memoria / spazio su disco.
Dai un'occhiata ad alcuni benchmark: http://www.newLISP.org/benchmarks/
Molte funzioni per cui altri linguaggi richiedono l'utilizzo di moduli esterni sono già incorporate in newLISP. Funzioni di networking e metodi matematici come FFT (Fast Fourier Analysis) o funzioni di apprendimento automatico bayesiano sono rapidissime in newLISP. Sono funzioni integrate e non richiedono alcun modulo esterno. Nonostante ciò, newLISP è più piccolo di altri linguaggi di scripting.
5. newLISP ha le matrici?
-------------------------
Sì. Per le applicazioni con accesso random a liste di grandi dimensioni, l'accesso può essere effettuato più velocemente utilizzando gli array di newLISP.
6. newLISP ha le tabelle hash?
------------------------------
newLISP utilizza alberi binari red-black per l'accesso alla memoria associativa quando si gestiscono spazi dei nomi (namespace), dizionari e per l'accesso ai valori-chiave simili alla tecnica hash.
7. newLISP ha una gestione automatica della memoria?
----------------------------------------------------
Sì. Ma non è il tipico processo di garbage collection che trovi in altri linguaggi interattivi. Proprio come la garbage collection dei tradizionali linguaggi, newLISP ricicla la memoria inutilizzata. Tuttavia, newLISP lo fa in un modo nuovo, molto più efficiente. La gestione della memoria di newLISP è sincrona senza pause improvvise nell'elaborazione che vengono osservate in linguaggi con garbage collection vecchio stile. L'esclusiva gestione automatica della memoria di newLISP è una delle ragioni della sua velocità, delle sue dimensioni ridotte e dell'uso efficiente della memoria.
Vedi anche: "Automatic Memory Management in newLISP" di Lutz Mueller
http://www.newLISP.org/MemoryManagement.html
8. newLISP può passare i dati per riferimento?
----------------------------------------------
Tutte le funzioni integrate passano liste e stringhe per riferimento sia in ingresso che in uscita. Per passare per riferimento a funzioni definite dall'utente, liste e stringhe possono essere raggruppati in spazi dei nomi particolari (context). Maggiori informazioni su questo argomento sul manuale utente. Dalla versione 10.2, FOOP passa per riferimento anche l'oggetto.
9. Come funziona il variable scoping in newLISP?
------------------------------------------------
newLISP ha uno scope dinamico applicato all'interno di contesti o spazi dei nomi separati lessicalmente. I namespace hanno un overhead molto piccolo e possono esisterne a milioni. I contesti in newLISP consentono la chiusura lessicale di più di una funzione lambda e di un oggetto. I contesti possono essere utilizzati per scrivere funzioni con scope lessicale con memoria, moduli software e oggetti. Ciò evita le insidie dello scope dinamico e aiuta a strutturare programmi più grandi.
10. newLISP gestisce il multiprocessing?
----------------------------------------
Le versioni Linux / UNIX di newLISP possono eseguire il fork e lo spawn dei processi. Le versioni di Windows possono avviare processi figlio indipendenti. I semafori vengono utilizzati per sincronizzare i processi e la memoria condivisa può essere utilizzata per le comunicazioni tra i processi.
Su macOS, Linux e altri Unix, l'API Cilk è integrata per facilitare il lancio e la sincronizzazione di più processi, in modo trasparente senza preoccuparsi di semafori, blocchi, ecc. È disponibile un'API di messaggistica asincrona per comunicare tra processi.
11. Posso usare newLISP per compiti di calcolo distribuiti?
-----------------------------------------------------------
Alcune delle applicazioni più grandi di oggi vengono distribuite su più computer, dividendo le loro complesse attività tra più nodi su una rete. newLISP può essere eseguito come server per valutare i comandi inviati da altri client newLISP ad esso connessi. La funzione "net-eval" incapsula tutta la gestione della rete necessaria per comunicare con altri computer sulla rete, distribuire il codice e le attività di calcolo e raccogliere i risultati in un modo bloccante o basato sugli eventi. newLISP può anche fungere da server Web che gestisce le richieste HTTP incluso CGI.
12. Possiamo utilizzare la metodologia di programmazione orientata agli oggetti?
--------------------------------------------------------------------------------
newLISP offre un nuovo modo di programmazione orientata agli oggetti funzionale chiamata FOOP. Usa gli spazi dei nomi per raccogliere tutti i metodi per una classe di oggetti e usa le normali espressioni S per rappresentare gli oggetti. Per ulteriori dettagli su questo nuovo modo di programmazione orientata agli oggetti in newLISP consultare la serie di video di addestramento "Towards FOOP" nella sezione documentazione e il capitolo "Functional object-oriented programming" nel manuale utente. Dalla versione 10.2 gli oggetti FOOP sono mutabili.
13. Cosa sono pacchetti e moduli?
----------------------------------
newLISP utilizza gli spazi dei nomi per la creazione di pacchetti e moduli. Esistono moduli per l'accesso ai database come MySQL, PostgreSQL e SQLite, nonché ODBC. I moduli aggiuntivi supportano i protocolli Internet FTP, POP3, SMTP e REST. Poiché i nuovi spazi dei nomi di LISP vengono chiusi lessicamente, newLISP consente ai programmatori di trattare i moduli come black box. Questo metodologia è adatta per gruppi di programmatori che lavorano su applicazioni di grandi dimensioni.
newLISP può anche chiamare funzioni di librerie C condivise su Linux / UNIX e sistemi operativi Windows per espandere le sue funzionalità.
I moduli possono essere documentati utilizzando il sistema di documentazione automatica newLISPdoc.
14. Quali sono alcune differenze tra newLISP e altri LISP?
----------------------------------------------------------
Le nuove differenze di LISP dagli altri LISP includono: il funzionamento delle espressioni lambda, l'esistenza di namespace (o contesti), il passaggio parametri e, naturalmente, la API di newLISP (repertorio di funzioni). Nel complesso, il nuovo modo di programmazione del LISP di newLISP lo rendono più veloce, più piccolo e più facile da capire e da apprendere. Per una discussione più dettagliata, vedere "Comparison to Common Lisp and Scheme":
http://www.newLISP.org/index.cgi?page=Differences_to_Other_LISPs
15. newLISP funziona sul sistema operativo XYZ?
-----------------------------------------------
Probabilmente si. newLISP ha un minimo di dipendenze. Utilizza solo librerie C standard per la compilazione. Se il tuo sistema ha strumenti GNU come il compilatore GCC e l'utility make, allora newLISP dovrebbe compilare e linkare immediatamente usando uno dei makefile contenuti nella sua distribuzione sorgente.
newLISP viene creato utilizzando uno dei numerosi makefile, ciascuno scritto per una piattaforma specifica. Non ci sono script di make complessi. I makefile sono brevi e facili da modificare e adattare se non sono già inclusi nella tua piattaforma o configurazione.
16. newLISP può gestire i caratteri speciali del mio paese e della mia lingua?
------------------------------------------------------------------------------
Nella maggior parte del mondo occidentale, è sufficiente impostare le impostazioni internazionali utilizzando la funzione newLISP "set-locale".
Più della metà dei paesi del mondo usano una virgola decimale invece di un punto decimale. newLISP leggerà e scriverà correttamente le virgole decimali quando passerà alla corretta locale.
La maggior parte degli alfabeti nell'emisfero occidentale si adattano a tabelle di codici carattere a 256 codici e ogni carattere richiede un solo byte di 8 bit da codificare. Se la lingua del tuo paese richiede caratteri multibyte per codificarla, allora hai bisogno della versione di newLISP con supporto UTF-8 abilitato. I Makefile per Windows e Linux sono inclusi per compilare le versioni UTF-8 di newLISP. Nella versione UTF-8, molte funzioni di gestione dei caratteri sono in grado di gestire caratteri multibyte. Vedere il capitolo sulla localizzazione e UTF-8 nel manuale per i dettagli.
17. L'indicizzazione implicita non infrange le regole di sintassi del LISP?
---------------------------------------------------------------------------
Al contrario, l'indicizzazione implicita è un'estensione logica della sintassi LISP. Quando si valutano le espressioni S, il primo elemento viene applicato come una funzione agli elementi restanti nell'espressione che servono come argomenti della funzione. L'indicizzazione implicita consiste semplicemente nel considerare i membri dei tipi di dati numerici, di stringa e di elenco come operatori speciali di indicizzazione quando si trovano nella prima posizione di un'espressione S.
18. newLISP può essere incorporato in altri programmi?
------------------------------------------------------
newLISP può essere compilato come libreria condivisa UNIX o DLL Windows (libreria a collegamento dinamico). Di conseguenza, le versioni di libreria condivisa di newLISP possono essere utilizzate all'interno di altri programmi che sono in grado di importare funzioni di libreria condivisa. Altri modi per integrare la tua applicazione con newLISP includono i pipe I/O e le porte di rete.
Sui sistemi Win32, newLISP è stato utilizzato all'interno di MS Excel, MS Visual Basic e del generatore di applicazioni GUI NeoBook. Su UNIX, newLISP è stato utilizzato all'interno del foglio di calcolo di GNumeric. Su macOS, newLISP è stato utilizzato come linguaggio di estensione per l'editor di BBEdit grazie alla nuova LISP che comunica con BBEdit tramite i pipe di I/O standard. Il Guiserver basato su Java e il vecchio frontend Tcl/Tk per newLISP sono esempi di integrazione di newLISP tramite porte di rete.
19. Copyright sui miei script anche se newLISP è concesso in licenza GPL?
-------------------------------------------------------------------------
Si, puoi. Le FAQ di gnu.org per la GPL lo spiegano. Finché i tuoi script non usano altro software GPL di terze parti sotto forma di librerie importate o moduli caricati, i tuoi script in newLISP non devono necessariamente avere una licenza GPL. La maggior parte dei moduli sul sito Web di newLISP non ha licenza e non importa altre librerie. Se lo fanno, consultare le licenze di quelle librerie di terze parti.
newLISP ti permette di distribuire un binario dell'interprete insieme al tuo sorgente. Quando si utilizza newLISP nel software, menzionare sempre il sito Web www.newLISP.org nella documentazione come luogo in cui è disponibile il codice sorgente per newLISP.
20. Dove posso segnalare eventuali bug?
---------------------------------------
La maggior parte delle segnalazioni di bug risulta dalla mancata lettura della documentazione o dal ritenere che newLISP funzioni come Common Lisp o Scheme. Le domande, i commenti e le segnalazioni di bug sono pubblicati sul forum ufficiale, dove vengono letti da molti altri, dando loro l'opportunità di commentare o dare consigli. Il forum consente anche di inviare messaggi privati.
21. Posso compilare i miei script in programmi eseguibili?
----------------------------------------------------------
Si. Il comando: newLISP -x "myscript.lsp" "myscript.exe" genera un file eseguibile sul proprio sistema operativo.
============================================================================
newLISP in 21 minuti (John W. Small)
============================================================================
newLISP: un tutorial interattivo
--------------------------------
Questo documento è stato riformattato per HTML con alcune correzioni e aggiornamenti fatti da Rick Hanson nel maggio 2006, [email protected]. Ulteriori aggiornamenti da LM gennaio 2008, dicembre 2011, novembre 2014, maggio 2018.
Traduzione in italiano, aggiornamenti e adattamenti fatti da cameyo 2019.
Copyright 2004, John W. Small, Tutti i diritti riservati
Puoi scaricare e installare newLISP dal sito web www.newLISP.org.
Si prega di inviare eventuali commenti o domande riguardanti questo tutorial a [email protected].
Indice
------
Ciao Mondo!
Codice sorgente e dati sono intercambiabili
Argomenti di funzione
Effetti collaterali e contesti
Sequenze di espressioni
Eseguibili e librerie dinamiche (dll)
Binding (associazione/legame)
Lista come struttura ricorsiva
Funzioni
Funzioni di ordine superiore
Liste lambda
Ambito dinamico (Dynamic scope)
Lista degli argomenti di una funzione
Lambda-macro
Contesti
Ambito lessicale (Lexical scope)
Ciao Mondo!
-----------
Con newLISP installato sul tuo sistema, al prompt della riga di comando della shell (cmd in windows) inserisci newLISP per avviare la REPL (Read, Eval, Print, Loop).
Su Linux, la console sarebbe simile a questa:
$ newLISP
> _
E su piattaforme Windows, sarebbe simile a questa.
c:\> newLISP
> _
Dopo l'avvio, newLISP risponde con il simbolo del prompt.
> _
Nota del traduttore:
per utilizzare questo documento con notepad++ e la REPL di newLISP ho eliminato il simbolo del prompt ">" quando viene seguito da un'espressione (in questo modo è possibile eseguire l'espressione direttamente). Inoltre l'output della REPL viene preceduto dalla stringa "->".
Inserisci l'espressione qui sotto per stampare "Ciao Mondo!" sulla console.
(println "Ciao Mondo!")
newLISP stampa il valore dell'espressione immessa nel prompt della REPL prima di eseguire il ciclo e richiedere un nuovo input.
(println "Ciao Mondo!")
;-> Ciao Mondo!
;-> "Ciao Mondo!"
> _
Perché è stato stampato due volte?
La funzione println stampa la prima riga, es. Ciao Mondo! nella console a causa effetto collaterale (side effect) della chiamata di funzione.
Inoltre la funzione println restituisce la stringa di valore "Ciao Mondo!", cioè il suo ultimo argomento, alla REPL che a sua volta stampa la seconda riga, cioè
"Ciao Mondo!"
La REPL valuta qualsiasi espressione e non solo le chiamate di funzione:
"Ciao Mondo!"
;-> "Ciao Mondo!"
> _
Se inserisci l'espressione stringa "Ciao Mondo!", come mostrato sopra, questa restituisce semplicemente se stessa come qualsiasi espressione letterale e come i numeri letterali.
1
;-> 1
> _
A questo punto potresti essere intimorito dalle parentesi. Se iniziate newLISP conoscendo un normale linguaggio informatico, sembrerebbe più naturale scrivere una chiamata di funzione nel modo seguente:
println ("Ciao Mondo!")
Dovrai solo credermi sulla parola - nel tempo preferirai di gran lunga:
(println "Ciao Mondo!")
a
println ("Ciao Mondo!")
per ragioni che non possono essere adeguatamente spiegate fino a quando non avrai visto molti più esempi di elaborazione di liste simboliche.
Codice sorgente e dati sono intercambiabili
-------------------------------------------
Lisp è l'acronimo di List Processor. Poiché le liste sono utilizzate per rappresentare sia il codice che i dati in Lisp, questi ultimi sono essenzialmente intercambiabili.
La precedente espressione println è in realtà una lista con due elementi:
(println "Ciao mondo!")
Il primo elemento è:
println
e l'ultimo elemento è:
"Ciao Mondo!"
Lisp interpreta sempre una lista come una chiamata di funzione, a meno che non venga "quotata", indicando così che dovrebbe essere presa come un'espressione simbolica, cioè come un dato.
Per "quotare" occorre inserire il carattere " ' " davanti all'espressione.
'(println "Ciao Mondo!")
;-> (println "Ciao Mondo!")
> _
Un'espressione simbolica può tuttavia essere valutata come codice sorgente con la funzione "eval".
(eval '(println "Ciao Mondo!"))
;-> Ciao Mondo!
;-> "Ciao Mondo!"
> _
Un programma Lisp può modificare se stesso durante l'esecuzione (runtime) costruendo liste di dati ed eseguendoli come codice sorgente!
(eval '(eval '(println "Ciao Mondo!")))
;-> Ciao Mondo!
;-> "Ciao Mondo!"
> _
In realtà il carattere " ' " rappresenta la funzione quote (syntactical sugar).
(quote (println "Ciao Mondo!"))
;-> (println "Ciao Mondo!")
> _
Pensa alla funzione quote come una funzione che utilizza i suoi argomenti letteralmente, cioè come simboli.
'x
;-> x
(quote x)
;-> x
'(1 2 tre "quattro")
;-> (1 2 tre "quattro")
> _
I simboli, come x e tre sopra, e le liste simboliche svolgono un ruolo di vitale importanza nell'intelligenza artificiale (AI). Questo tutorial non riguarderà argomenti di AI. Tuttavia, una volta che avrai imparato a programmare in Lisp, sarai in grado di seguire tranquillamente gli esempi Lisp che si trovano nella maggior parte dei libri di testo su AI.
Considera il seguente esempio.
'Ciao
;-> Ciao
"Ciao"
;-> "Ciao"
> _
Il simbolo 'Ciao non è lo stesso della stringa "Ciao". Ora puoi capire perché la REPL stampa le virgolette per indicare una stringa, distinguendola quindi da un simbolo con le stesse lettere.
Argomenti di funzione
---------------------
La funzione println può avere un numero variabile di argomenti.
(println "Ciao " "Mondo!")
;-> Ciao Mondo!
;-> "Mondo!"
> _
Gli argomenti sono semplicemente concatenati attraverso il flusso di output mentre l'ultimo argomento viene restituito come valore della chiamata di funzione.
In genere, gli argomenti passati a una funzione vengono valutati da sinistra a destra e i valori risultanti vengono quindi passati alla funzione. Si dice che gli argomenti correnti di una funzione sono valutati in modo rigoroso. Questo è noto come valutazione applicata in base all'ordine (applicative-order evaluation).
Ma notate che, per la funzione quote, questo non è il caso:
(quote (println "Ciao Mondo!"))
;-> (println "Ciao Mondo!")
> _
Se il suo argomento, vale a dire:
(println "Ciao Mondo!")
fosse stato rigorosamente valutato, avremmo visto:
Ciao Mondo!
visualizzato sulla console.
La funzione di quote è una funzione atipica a volte definita "forma speciale".
Puoi scrivere le tue funzioni speciali con newLISP. Queste sono chiamate macro e i loro argomenti sono detti "chiamati per nome", cioè letteralmente.
Questo è noto come ordine di valutazione normale e diciamo che la strategia di valutazione è pigra (lazy). In altre parole, gli argomenti di una macro non vengono valutati fino a quando, e solo se, si specifica direttamente l'esecuzione della valutazione (come vedremo in seguito).
Quindi, l'argomento della funzione quote viene preso alla lettera e restituito. In un certo senso, quote è una funzione di identità con una strategia di valutazione pigra (lazy evaluation). Non si preoccupa mai di valutare i sui argomenti, invece la restituisce letteralmente nella sua forma simbolica di codice sorgente.
Senza forme speciali, i costrutti di controllo del flusso trovati in altri linguaggi non potrebbero essere implementati in una linguaggio con solo liste di espressioni come sintassi con cui lavorare. Ad esempio, considera il seguente if:
(if true (println "Ciao") (println "Arrivederci"))
;-> Ciao
;-> "Ciao"
> _
La forma speciale if prende tre argomenti:
sintassi: (if condizione conseguenza alternativa)
condizione => vero
conseguenza => (println "Ciao")
alternativa => (println "Arrivederci")
L'argomento della condizione viene sempre valutato (strict evaluation), ma le conseguenze e le espressioni alternative sono valutate in modo pigro (lazy). Inoltre l'espressione alternativa è facoltativa.
Si noti che if è un'espressione. Restituisce il valore della espressione conseguenza o dell'espressione alternativa a seconda che la condizione sia rispettivamente vera (true) o falsa. Nell'esempio sopra, sappiamo che l'espressione alternativa non è stata valutata, perché il suo effetto collaterale della stampa "Arrivederci" sulla console non si è mai verificato.
Il valore di un'espressione if con una condizione falsa che non ha alternative e vale semplicemente nil (nullo). Il valore nil (nullo) indica vuoto o falso a seconda dell'interpretazione richiesta.
Nota: nella maggior parte dei linguaggi di programmazione tradizionali if è un'istruzione, e quindi non ha un valore di ritorno.
Se il Lisp non avesse avuto una strategia di valutazione pigra (lazy), non sarebbe possibile implementare forme speciali o macro. Senza una strategia di valutazione pigra, sarebbe stato necessario aggiungere parole chiave e/o sintassi al linguaggio. Quale tipi di sintassi hai visto fino ad ora, oltre alla parentesi e alle virgolette? Risposta: non molto!
Il rovescio della valutazione pigra (lazy) è che ora possibile aggiungere il proprio controllo di flusso al linguaggio estendendo così la "sintassi" di Lisp che consente di incorporare mini-linguaggi specifici dell'applicazione. La scrittura di funzioni e di macro sarà trattata in una sezione successiva di questo tutorial.
Effetti collaterali e contesti
------------------------------
Senza effetti collaterali, avere un REPL sarebbe inutile. Per capire il perché, consideriamo la seguente sequenza di espressioni:
(set 'ciao "Ciao")
;-> "Ciao"
(set 'mondo " Mondo")
;-> " Mondo"
(println ciao mondo)
;-> Ciao Mondo
;-> "Mondo"
> _
La funzione set sopra ha un effetto collaterale, come dimostrato di seguito:
ciao
;-> "Ciao"
mondo
;-> " Mondo"
> _
I simboli 'ciao e 'mondo sono legati nel contesto corrente a "Ciao" e "Mondo" rispettivamente.
Tutte le funzioni integrate (built-in) sono associate a simboli del contesto MAIN.
println
println@<409040>
set
set@<4080D0>
> _
Questo ci dice che println è associato a una funzione chiamata println con un punto di ingresso di 409040 (Versioni (build) diverse di newLISP avranno ovviamente punti di ingresso diversi per println).
Il contesto predefinito è MAIN. Un contesto è essenzialmente uno spazio dei nomi di stato. Impareremo in seguito i contesti definiti dall'utente.
Si noti che il simbolo letterale 'ciao valuta se stesso:
'ciao
;-> ciao
> _
La valutazione del simbolo 'ciao restituisce il valore a cui è associato nel contesto corrente:
(eval 'ciao)
;-> "Ciao"
> _
Se il simbolo non è associato quando viene valutato, restituisce semplicemente nil:
(eval 'z)
;-> nil
> _
In realtà non abbiamo bisogno di eval, dal momento che il simbolo senza la funzione quote viene automaticamente valutato nel contesto attuale:
ciao
;-> "Ciao"
z
;-> nil
> _
Quindi il valore di ciao e di mondo sono "Ciao" e "Mondo" rispettivamente:
(println ciao mondo)
;-> Ciao Mondo
;-> "Mondo"
> _
Cosa verrebbe visualizzato se inseriamo quanto segue?
(println 'ciao 'mondo)
?
Pensaci per un momento.
La funzione println visualizza i simboli uno immediatamente dopo l'altro sulla prima riga:
(println 'ciao 'mondo)
;-> ciaomondo
;-> mondo
> _
Sequenze di espressioni
-----------------------
Una sequenza di espressioni può essere combinata in un'espressione composta con la funzione begin:
(begin "Ciao" " Mondo!")
;-> " Mondo!"
> _
Cosa è successo a "Ciao"? Poiché un'espressione composta restituisce un singolo valore, restituisce il valore della sua ultima espressione. Ma le espressioni sono infatti valutate in sequenza. È solo che l'espressione "Ciao" non ha alcun effetto collaterale, quindi il suo valore di ritorno viene scartato e non si vede mai alcuna prova della sua valutazione:
(begin (print "Ciao") (println " Mondo!"))
;-> Ciao Mondo!
;-> " Mondo!"
> _
Questa volta, gli effetti collaterali di print e println sono evidenziati nella finestra della console e l'ultimo valore restituito viene visualizzato dal REPL.
La funzione begin è utile per combinare espressioni in una singola espressione. Ricordiamo la forma speciale if:
(if true