LoginSignup
4
3

More than 5 years have passed since last update.

Scheme手習いメモ (1章 - おもちゃ)

Last updated at Posted at 2012-08-18

準備

  • 本を購入
  • Gaucheをインストール
  • Vimで、編集中のコードを実行したいときは :!gosh % でできる。

本編

atom?, list?

とりあえずSchemeを書いてみたかったので、p.3に書いてあるコードをちょっと変えて試してみる。

p3.scm
;p.xiii に掲載されているアトムを判定するっぽい関数
(define atom?
    (lambda (x)
        (and (not (pair? x)) (not (null? x)))))
;#t, #fがtrue, falseに対応するっぽい
;評価の結果は表示されないみたいなので、printで出力してみる
(print (atom? (quote 0)))
;出力 : #t

;ここからp.3
(print (atom? 'atom))
(print (atom? 'turkey))
(print (atom? 1483))
(print (atom? 'u))
(print (atom? '*abc$))

;リストかどうか判定するのはlist?かしらん
(print (list? '(atom)))
(print (list? '(atom turkey or)))
;p.3一番下のはエラー

出力は以下のとおり。

:!gosh hello.scm
[No write since last change]
#t
#t
#t
#t
#t
#t
#t
#t     

アトムもリストもS式です。あと、空リストももちろんある。対話型インタプリタを使ってみる。 $gosh コマンドで起動。

gosh> (list? ())
#t

car

car というのがあるらしい。リストに含まれる一番目のS式を取り出す関数?

gosh> (car '(a b c))
a
gosh> (car '((a b c) x y z))
(a b c)
gosh> (car '(((hotdogs)) (and) (picke) relish))
((hotdogs))
(car (car '(((hotdogs)) (and) (picke) relish)))

ホットドッグ食べたくなってきた。

cdr

cdr はリストから car した要素を取り除いたリストを返す。

gosh> (cdr '(a b c))
(b c)
gosh> (cdr '(hamburger))
()

cons

cons は任意のS式をリストの最初の要素として追加する関数。

gosh> (cons 'a '(better and jelly))
(a better and jelly)
gosh> (cons '(banana and) '(peanut butter and jelly))
((banana and) peanut butter and jelly)
gosh> (cons 'a (car '((b) c d)))
(a b)

null?

null? で空リストか判定できる。

gosh> (null? '()) 
#t

eq?

eq?で二つの数値以外のアトムが等しいか判定できる。

gosh> (eq? 'Harry 'Harry)
#t
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3