'Programming'에 해당되는 글 1721건

  1. 2013.01.22 lisp eval & apply
  2. 2013.01.19 xlisp에서 incf 오류
  3. 2013.01.19 lisp backquote / 유사인용
  4. 2013.01.17 lisp rem, mod
  5. 2013.01.17 lisp i/o
  6. 2013.01.17 lisp file i/o
  7. 2013.01.16 lisp savefun / load
  8. 2013.01.16 xlisp
  9. 2013.01.14 lisp 연관리스트
  10. 2013.01.14 lisp의 con cell 과 NIL
Programming/lisp2013. 1. 22. 22:39
"만들면서 배우는 리스프 프로그래밍" 123p

스스로 변화하는 코드를 짜고 싶은가? eval은 좋은 벗이 될 것이다. 사실, 과거 인공지능 연구가가 리스프를 그토록 사랑했던 이유가 여기에 있다.


eval은 데이터를 코드로 처리하는 기능을 한다.
위에 말 처럼 스스로 변화하는 코드라는 말까지 와닫지는 않지만
데이터가 코드가 되는 살아움직이는 느낌 정도는 받는다고 해야 하려나?

eval은 리스트로 된 문장을 evaluate 한다.(재귀적인가?)
'(+ 1 2)는 단순한 데이터로 실행되지 않지만 eval에 넣으면 수행을 하게 된다.
> (eval (+ 1 2)) 
3                
> (eval '(+ 1 2))
3                
>                 

그에 반해 apply는 머하는데 쓰는건지 조금 의아한 녀석..
> (apply (function +) '(1 2))
3
> (apply + '(1 2))                                     
error: bad function - (apply (function +) (quote (1 2)))                              
매크로를 사용하면 #'+ 가 되겠지만 명시적으로  (function)을 사용해보면 위와 같이
함수에 대한 포인터(?)를 이용하여 eval에서 연산자를 제외한 동일한 형상을 띄게 된다


evaluate an xlisp expression
(eval <expr>)

<expr> the expression to be evaluated
returns the result of evaluating the expression

apply a function to a list of arguments
(apply <fun> <arg>...<args>)

<fun> the function to apply (or function symbol). May not be macro or fsubr.
<arg> initial arguments, which are consed to...
<args> the argument list
returns the result of applying the function to the arguments  

'Programming > lisp' 카테고리의 다른 글

lisp when/unless macro  (2) 2013.01.28
lisp 명령어 if progn  (0) 2013.01.28
xlisp에서 incf 오류  (0) 2013.01.19
lisp backquote / 유사인용  (0) 2013.01.19
lisp rem, mod  (0) 2013.01.17
Posted by 구차니
Programming/lisp2013. 1. 19. 23:36
xlisp에서 제대로 지원을 안해서 생기는 문제인가?

xlisp 도움말에도 존재는 하지만
increment a field
(incf <place> [<value>])
decrement a field
(decf <place> [<value>])

defined as macro in common.lsp.  Only evaluates place form arguments one time.  It is recommended that *displace-macros* be non-nil for best performance.

<place> field specifier being modified (see setf)
<value> Numeric value (default 1)
returns the new value which is (+ <place> <value>) or (- <place> <value>) 

xlisp에서 이상하게 unbound function 이라고 뜬다.
> (setq a 1)                              
1                                         
> (incf a)                                
error: unbound function - incf            
if continued: try evaluating symbol again 

clisp에서 실행 이상없음
[9]> (setq a 1)
1
[10]> (incf a)
2
[11]> a
2 

윈도우에서 편해서 이걸 쓰지만.,.
slime for windows나 cygwin으로 해야하려나? ㅠ.ㅠ 

'Programming > lisp' 카테고리의 다른 글

lisp 명령어 if progn  (0) 2013.01.28
lisp eval & apply  (0) 2013.01.22
lisp backquote / 유사인용  (0) 2013.01.19
lisp rem, mod  (0) 2013.01.17
lisp i/o  (0) 2013.01.17
Posted by 구차니
Programming/lisp2013. 1. 19. 23:19
어떻게 보면.. printf()의 기분?

> (defun tt-path (edge)                                               
'(there is a ,(caddr edge) going, (cadr edge) from here.))            
tt-path                                                               
> (tt-path '(garden west door))                                       
(there is a (comma (caddr edge)) going (comma (cadr edge)) from here.) 

> (defun t2-path (edge)                                   
`(there is a ,(caddr edge) going, (cadr edge) from here.))
t2-path                                                   
> (t2-path '(garden west door))                           
(there is a door going west from here.)                   

'Programming > lisp' 카테고리의 다른 글

lisp eval & apply  (0) 2013.01.22
xlisp에서 incf 오류  (0) 2013.01.19
lisp rem, mod  (0) 2013.01.17
lisp i/o  (0) 2013.01.17
lisp file i/o  (0) 2013.01.17
Posted by 구차니
Programming/lisp2013. 1. 17. 19:26
reminder 나 modulo 나 둘다 나머지 연산인데
왜 굳이 두개의 이름으로 별도로 존재하나 했더니

양수에서는 차이가 없으나, 음수에서 차이가 발생한다.
2> (mod  5 2) 
1             
2> (mod  5 -2)
-1            
2> (rem  5 2) 
1             
2> (rem  5 -2)
1              


    Rem(x, 5):

                       5+         o         o
                        |       /         /
                        |     /         /
                        |   /         /
                        | /         /
    *---------*---------*---------*---------*
   -10      / -5      / 0         5        10
          /         /   |
        /         /     |
      /         /       |
    o         o       -5+

    Mod(x, 5):

              o        5o         o         o
            /         / |       /         /
          /         /   |     /         /
        /         /     |   /         /
      /         /       | /         /
    *---------*---------*---------*---------*
   -10        -5        0         5        10

    Rem(x, -5):

                       5+         o         o
                        |       /         /
                        |     /         /
                        |   /         /
                        | /         /
    *---------*---------*---------*---------*
   -10      / -5      / 0         5        10
          /         /   |
        /         /     |
      /         /       |
    o         o       -5+

    Mod(x, -5):

    *---------*---------*---------*---------*
   -10      / -5      / 0       / 5       /10
          /         /   |     /         /
        /         /     |   /         /
      /         /       | /         /
    o         o       -5o         o
 
[링크 : http://mathforum.org/library/drmath/view/54377.html

'Programming > lisp' 카테고리의 다른 글

xlisp에서 incf 오류  (0) 2013.01.19
lisp backquote / 유사인용  (0) 2013.01.19
lisp i/o  (0) 2013.01.17
lisp file i/o  (0) 2013.01.17
lisp savefun / load  (0) 2013.01.16
Posted by 구차니
Programming/lisp2013. 1. 17. 18:53
c언어로 치면 printf() 와 scanf()인데
어짜피 stream 이기 때문에 file을 열어 놓은 스트림을
read나 printf 계열 함수에 연결해서 써도 문제는 없을듯 하니
c언어 보다 더욱 범용성이 있어 보인다고 해야하나
c보다는 리눅스의 FMIO(File Mapped IO)에 가까운 느낌이라고 해야하나?

read an expression
(read [<stream> [<eofp> [<eof> [<rflag>]]]])

print an expression on a new line
(print <expr> [<stream>])

print an expression
(prin1 <expr> [<stream>])

print an expression without quoting
(princ <expr> [<stream>])

pretty print an expression
(pprint <expr> [<stream>])

print to a string
(prin1-to-string <expr>)
(princ-to-string <expr>) 

> (print "test string") 
"test string"           
"test string"           
> (print '(test string))
(test string)           
(test string)            
 
> (princ "test string") 
test string             
"test string"           
> (princ '(test string))
(test string)           
(test string)           

> (prin1 "test string") 
"test string"           
"test string"           
> (prin1 '(test string))
(test string)           
(test string)           

'Programming > lisp' 카테고리의 다른 글

lisp backquote / 유사인용  (0) 2013.01.19
lisp rem, mod  (0) 2013.01.17
lisp file i/o  (0) 2013.01.17
lisp savefun / load  (0) 2013.01.16
xlisp  (0) 2013.01.16
Posted by 구차니
Programming/lisp2013. 1. 17. 18:50
C언어로 치면 feopn() / fclose() / fseek() / fread()

xlisp.exe의 경로에 생성됨.
ubuntu의 clisp는 실행된 "현재경로"에 생성됨.
> (setq out-stream (open "my-temp-file"))                    
error: file does not exist - "my-temp-file"                  
1> (setq out-stream (open "my-temp-file" :direction :output))
#<Character-Output-Stream 4:"my-temp-file">                  
1> (close out-stream)                                        
t                                                            
1> (setq out-stream (open "my-temp-file"))                   
#<Character-Input-Stream 4:"my-temp-file">                   
1> (close out-stream)                                        
t                                                            
1>                                                            

[링크 : http://psg.com/~dlamkins/sl/chapter03-11.html]

open a file stream
(open <fname> &key :direction :element-type :if-exists :if-does-not-exist)

close a file stream
(close <stream>)

check for existance of a file
(probe-file <fname>)

delete a file
(delete-file <fname>)

get length of file
(file-length <stream>)

get or set file position
(file-position <stream> [<expr>])

read a byte from a stream
(read-byte <stream>[<eofp>[<eof>]])

write a byte to a stream
(write-byte <byte> <stream>)

'Programming > lisp' 카테고리의 다른 글

lisp rem, mod  (0) 2013.01.17
lisp i/o  (0) 2013.01.17
lisp savefun / load  (0) 2013.01.16
xlisp  (0) 2013.01.16
lisp 연관리스트  (0) 2013.01.14
Posted by 구차니
Programming/lisp2013. 1. 16. 22:05
xlisp의 경우 실행파일 위치가 XLPATH 인듯 하고
해당 위치에 자동으로 *.lsp 파일을 읽거나 저장한다.

load a source file
(load <fname> &key :verbose :print)

An implicit errset exists in this function so that if error occurs during loading, and *breakenable* is NIL, then the error message will be printed and NIL will be returned.  The OS environmental variable XLPATH is used as a search path for files in this function.  If the filename does not contain path separators ('/' for UNIX, and either '/' or '\' for MS-DOS) and XLPATH is defined, then each pathname in XLPATH is tried in turn until a matching file is found.  If no file is found, then one last attempt is made in the current directory.  The pathnames are separated by either a space or semicolon, and a trailing path separator character is optional.

<fname> the filename string, symbol, or a file stream created with open. The extension "lsp" is assumed.
:verbose the verbose flag (default is T)
:print the print flag (default is NIL)
returns T if successful, else NIL 

save function to a file
(savefun <fcn>)

defined in init.lsp

<fcn> function name (saves it to file of same name, with extension ".lsp")
returns T if successful  


사용예
> (defun add (a b) (+ a b))
add                        
> (savefun add)            
"ADD.lsp"                   

> (load "add")        
; loading "add.lsp"    
t                      
> (add 2 3)           
5                      
> #'add               
#<Closure-ADD: #9b92b0> 

'Programming > lisp' 카테고리의 다른 글

lisp i/o  (0) 2013.01.17
lisp file i/o  (0) 2013.01.17
xlisp  (0) 2013.01.16
lisp 연관리스트  (0) 2013.01.14
lisp의 con cell 과 NIL  (0) 2013.01.14
Posted by 구차니
Programming/lisp2013. 1. 16. 21:44
xlisp에서 하다보면

1>
2>

이런식으로 숫자가 에러가 날때마다 늘어나는데
무언지 어떻게 줄이는지 몰라서 찾다보니
xlisp 도움말에 다음과 같은 내용이 있었다.

ctrl-c나 ctrl-g를 통해서 한단계 위로 간다고 해도
setq 등을 통해서 선언한 변수는 그대로 살아있다.

XLISP then issues the following prompt (unless standard input has been redirected):

>

This indicates that XLISP is waiting for an expression to be typed.  If the current package is other than user, the the package name is printed before the ">".

When a complete expression has been entered, XLISP attempts to evaluate that expression. If the expression evaluates successfully, XLISP prints the result and then returns for another expression.

The following control characters can be used while XLISP is waiting for input:


Backspace delete last character
Del delete last character
tab tabs over (treated as space by XLISP reader)
ctrl-C goto top level
ctrl-G cleanup and return one level
ctrl-Z end of file (returns one level or exits program)
ctrl-P proceed (continue)
ctrl-T print information 

> (_)                                           
error: unbound function - _                     
if continued: try evaluating symbol again       
1>                                              ctrl-P
[ continue from break loop ]                    
error: unbound function - _                     
if continued: try evaluating symbol again       
1>                                              ctrl-T
[ Free: 7422, Total: 152117, GC calls: 2,       
  Edepth: 31183, Adepth 41579, Sdepth: 999588 ] 
                                                 ctrl-G
[ back to previous break level ]                
>                                                

> (_)                                     
error: unbound function - _               
if continued: try evaluating symbol again 
1>                                             ctrl-C 
[ back to top level ]
>                                          

'Programming > lisp' 카테고리의 다른 글

lisp file i/o  (0) 2013.01.17
lisp savefun / load  (0) 2013.01.16
lisp 연관리스트  (0) 2013.01.14
lisp의 con cell 과 NIL  (0) 2013.01.14
lisp #  (0) 2013.01.11
Posted by 구차니
Programming/lisp2013. 1. 14. 23:15
associative memory의 줄임말이려나?
아무튼 굳이 NIL로 끝나지 않는 리스트로 하지 않아도 상관은 없지만
(assoc '찾을값 찾을목록)
식으로 사용하면 된다. 하지만 linked list를 이용해서 검색하는 것으로 
성능상의 하락이 있으므로 해싱을 이용하는 등, 다른방법을 강구하는 것이 좋다고 한다.

(setq tt '((bill . double)
            (lisa . coffee)
            (john . latte)))
((BILL . DOUBLE) (LISA . COFFEE) (JOHN . LATTE))
> (assoc 'lisa tt)
(LIST . COFFEE)

(setq ta '((bill double)
            (lisa coffee)
            (john latte)))
((BILL DOUBLE) (LISA COFFEE) (JOHN LATTE))
> (assoc 'lisa ta)
(LIST . COFFEE)


'Programming > lisp' 카테고리의 다른 글

lisp savefun / load  (0) 2013.01.16
xlisp  (0) 2013.01.16
lisp의 con cell 과 NIL  (0) 2013.01.14
lisp #  (0) 2013.01.11
만들면서 배우는 리스프 프로그래밍  (2) 2013.01.09
Posted by 구차니
Programming/lisp2013. 1. 14. 23:04
lisp는 이름 그대로 LISt Processing으로
LIST를 기반으로 작업하게 된다.

자료구조에서 배우던 linked list를 이용해서 자료를 저장하게 되는데
C언어에서 항상 문자열은 0x00 혹은 \0으로 끝맺듯
list 도 마지막은 NIL로 표기를 하게 된다.

아래는 NIL로 끝나지 않는 리스트와 NIL로 끝나는 리스트를 만든것으로
. 은 NIL로 끝나지 않는 리스트를 의미하게 된다. 
[1]> '(1 . 2)
(1 . 2)
[2]> (cons 1 2)
(1 . 2)
[3]> '(1 2)
(1 2)
[4]> (cons 1 (cons 2 NIL))
(1 2)
 

last는 안되고 아무튼 rest는 남은걸 나타내는 것이기 때문에 가능한 것 같은데
(1 2)에 대한 rest 두번은 NIL이 나오고
(1 . 2) 에 대한 rest 두번은 존재하지 않기 때문에 에러가 발생하게 된다.
[6]> (rest (rest '(1 2)))
NIL
[6]> (rest (rest '(1 . 2)))

*** - REST: 2 is not a list
The following restarts are available:
ABORT          :R1      Abort debug loop
ABORT          :R2      Abort main loop
[7]> (rest '(1 . 2))
2


그나저나.. 책에 의하면 아래와 같이 뜬다고 하는데
> (defparameter foo '(1 2 3))
FOO
> (setf (cdddr foo) foo)
#1=(1 2 3 . #1#) 

내가 사용하는 clisp 2.49에서는 뻗어버린다 -_-
  i i i i i i i       ooooo    o        ooooooo   ooooo   ooooo
  I I I I I I I      8     8   8           8     8     o  8    8
  I  \ `+' /  I      8         8           8     8        8    8
   \  `-+-'  /       8         8           8      ooooo   8oooo
    `-__|__-'        8         8           8           8  8
        |            8     o   8           8     o     8  8
  ------+------       ooooo    8oooooo  ooo8ooo   ooooo   8

Welcome to GNU CLISP 2.49 (2010-07-07) <http://clisp.cons.org/>

Copyright (c) Bruno Haible, Michael Stoll 1992, 1993
Copyright (c) Bruno Haible, Marcus Daniels 1994-1997
Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998
Copyright (c) Bruno Haible, Sam Steingold 1999-2000
Copyright (c) Sam Steingold, Bruno Haible 2001-2010

Type :h and hit Enter for context help.
 
[12]> (defparameter foo '(1 2 3))
FOO
[13]> (setf (cdddr foo) foo)
^C
*** - Ctrl-C: User break
The following restarts are available:

*** - handle_fault error2 ! address = 0x68457000 not in [0x65de5658,0x68457000) !
SIGSEGV cannot be cured. Fault address = 0x68457000.
GC count: 47
Space collected by GC: 0 355764032
Run time: 40 918556
Real time: 164 950564
GC time: 23 933489
Permanently allocated: 94080 bytes.
Currently in use: 1194294496 bytes.
Free space: 12 bytes. 


'Programming > lisp' 카테고리의 다른 글

xlisp  (0) 2013.01.16
lisp 연관리스트  (0) 2013.01.14
lisp #  (0) 2013.01.11
만들면서 배우는 리스프 프로그래밍  (2) 2013.01.09
lisp 전역변수 / 지역변수  (0) 2013.01.09
Posted by 구차니