Drkcore

26 04 2007 SICP elisp Tweet

elispで高階関数

昨日弱音を吐いたけど、小鼓呑んで頭がまわってないだけだった。(どうしても日本酒が飲みたくてローソンで買った。ゴールデンウィークは実家に帰って会津とか那須のほうの酒を物色予定)

SICPのp.32はこんな感じで

(defun inc (n) (+ n 1))

(defun cube (x) (* x x x))

(defun sum (term a next b)
(if (> a b) 0
  (+ (funcall term a)
     (sum term (funcall next a) next b))))

(sum 'cube 1 'inc 10)
3025

関数はクォートして評価されないようにしといて、高階関数のほうでfuncallで評価する。こんな感じになってくるとなんかperlのリファレンス操作してるみたいだ。

とか思ったのでperlでも書いてみた。

my $inc = sub {$_[0] + 1};
my $cube = sub {$_[0] ** 3};

sub sum {
  my ($term,$a,$next,$b) = @_;
  return 0 if $a > $b;
  $term->($a) + sum($term,$next->($a),$next,$b);
}

print sum($cube,1,$inc,80);

Emacs辞典の4章がelispの基礎でわかりやすい。

ProductName Emacs 辞典 (DESKTOP REFERENCE)
佐藤 竜一
翔泳社 / 3129円 ( 2006-05-11 )


あと

(sum 'cube 1 'inc 51)

で

(error "Lisp nesting exceeds max-lisp-eval-depth")

っていうエラーがでた(Meadow)

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021