LoginSignup
10
2

More than 3 years have passed since last update.

Lispでパイプ演算子

Last updated at Posted at 2021-01-08

はじめに

ElixirやRubyなどモダンな言語にはパイプ演算子というちょっと便利な記法があります。Lispのマクロで取り入れてみました。コードはISLispで書いてありますが、Common-Lispでもそのまま動くと思います。

表記

(pipe 1 |> (foo 2) |> (bar 3) |> (boo 4))

このように表記することとします。これは次のS式と等価です。

(macroexpand-1 '(pipe 1 |> (foo 2) |> (bar 3) |> (boo 4))) 
;; #=> (BOO (BAR (FOO 1 2) 3) 4)

使い方

(defun foo (x y)
    (+ x y) )

(defun bar (x y)
    (* x y) )

(defun boo (x y)
    (- x y) )

(pipe 1 |> (foo 2) |> (bar 3) |> (boo 4)) 
;; #=> 5

実装

common_lisp
(defmacro pipe (:rest expr)
    (pipe-macro (cdr expr) (car expr)) )

(defun pipe-macro (pipe func)
    (cond ((null pipe) func)
          ((eq (car pipe) '|>) (pipe-macro (cdr pipe) func))
          (t (pipe-macro (cdr pipe) (pipe-macro1 (car pipe) func))) ))

(defun pipe-macro1 (fun funcs)
    (cons (car fun) (cons funcs (cdr fun))) )

Github

tests/pipe.lsp にコードがあります。

10
2
2

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
10
2