'Programming'에 해당되는 글 1762건

  1. 2013.01.28 lisp 명령어 if progn
  2. 2013.01.22 lisp eval & apply
  3. 2013.01.19 xlisp에서 incf 오류
  4. 2013.01.19 lisp backquote / 유사인용
  5. 2013.01.17 lisp rem, mod
  6. 2013.01.17 lisp i/o
  7. 2013.01.17 lisp file i/o
  8. 2013.01.16 lisp savefun / load
  9. 2013.01.16 xlisp
  10. 2013.01.14 lisp 연관리스트
Programming/lisp2013. 1. 28. 10:22
if문 예제
> (if (< 1 2) 'A 'B)
A
> (if (< 1 2) (if (< 1 2) 'C 'D) 'B)

생각해보니 lisp의 if는 if then-else 이지 if - else if - else 가 아닌것 같다.
물론 불편하지만 else if 대신 else 에 if를 중첩해서 쓰면 되긴 하지만
언어 컨셉이 다르니 c언어와 다르다고 해서 안좋아! 라고 하긴 그렇겠....지?

[링크 : http://gigamonkeys.com/book/macros-standard-control-constructs.html]


그리고 if문에서 lisp 안에 하나의 문장만 해결하기에는 2% 부족하니
sequence로 여러개의 실행을 할 수 있도록 하는 progn이 필요하다.
progn은 마지막 것을
progn1 은 처음 것
progn2 는 두번째 것을 return 한다.

[10]> (progn (print "The first form")
       (print "The second form")
       (print "The third form"))

"The first form"
"The second form"
"The third form"
"The third form"
 
[11]> (prog1 (print "The first form")
       (print "The second form")
       (print "The third form"))

"The first form"
"The second form"
"The third form"
"The first form"
 
[12]> (prog2 (print "The first form")
       (print "The second form")
       (print "The third form"))

"The first form"
"The second form"
"The third form"
"The second form" 

[링크 : http://www.delorie.com/gnu/docs/elisp-manual-21/elisp_125.html]



+++
두개를 조합하면?
> (if (> 2 3)
(progn (print "i am a boy") (print "you are a girl"))
(progn (print "tt") (print"aa")))

"tt"
"aa"
"aa" 

 

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

lisp cond  (0) 2013.01.28
lisp when/unless macro  (2) 2013.01.28
lisp eval & apply  (0) 2013.01.22
xlisp에서 incf 오류  (0) 2013.01.19
lisp backquote / 유사인용  (0) 2013.01.19
Posted by 구차니
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 구차니