LoginSignup
1
0

More than 5 years have passed since last update.

Scheme手習いメモ (2章 - 一度、もう一度、さらにもう一度、またもう一度…)

Last updated at Posted at 2012-12-26

lat?

与えられたリストが、アトムからなるリストか判定する関数 lat を定義する。

lat.scm
(define atom?
    (lambda (x)
        (and (not (pair? x)) (not (null? x)))))

(define lat?
  (lambda (l)
    (cond
      ((null? l) #t)
      ((atom? (car l))(lat? (cdr l)))
      (else #f))))

(print (lat? '(bacon and eggs)))
(print (lat? '(bacon (and eggs))))

最初の atom? の定義は本の序文に乗ってたやつ。で、 lat? が新しく定義した関数。 cond という関数でパターンマッチが行われて、再帰するのだと予想する。

コードを実行した出力結果は次の通り。

:!gosh lat.scm
#t  

(bacon and eggs) はアトムからなるリストなので、真になっている。 (bacon (and eggs)) は二つ目の要素がリストなので偽である。

or

ご存知 or が登場。ブール演算子ですね。

(define l '())
(define l2 '(d e f g))
(or (null? l) (atom? l2))

のように使える。真。 define を変数の代入に使ってみたのだけれど、使い方あってるのかこれ。

member?

続いて、ある要素がリストのメンバーか尋ねる関数 member? を定義する。

member.scm
(define member?
  (lambda (a lat)
    (cond
      ((null? lat) #f)
      (else (or (eq? (car lat) a)
                (member? a (cdr lat)))))))
> (define a 'meat)
> (define lat '(mashed potatoes and meat gravy))
> (member? a lat)
#t

2章まではサクサク進めた印象。再帰が分かっていれば、ここまでで躓くことは無さそう。3章も楽しみです。

1
0
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
1
0