🥀

『薔薇言語』動くコード詩集

に公開

すべてPythonで書かれた“動く”コードポエトリー50編です。
実行すると、各篇が生成・実行され、詩行が出力されます。
外部依存なし、標準ライブラリのみ。

from __future__ import annotations
import math, random, itertools as it, datetime as dt, hashlib, textwrap, statistics as stats

LINE = "—" * 40

def show(n, title, lines):
    print(LINE)
    print(f"{n:02d}. {title}")
    for s in lines:
        print(s)
    print()

# 01 例外に口づけ
def poem_01():
    title = "例外に口づけ"
    try:= True
        if:
            raise ValueError("血潮")
        else:
            raise RuntimeError("虚無")
    except Exception as e:
        lines = [
            f"if 愛: raise → {e}",
            "薔薇はデバッグの赤、",
            "スタックトレースは君の脈。",
            "exceptで掬った熱だけが生だ。"
        ]
    return title, lines

# 02 未定義の心臓
def poem_02():
    title = "未定義の心臓"
    心臓 = None
    lines = [
        f"心臓 = {心臓}",
        "print(None) は静寂の記号、",
        "鼓動はコメントに退避され、",
        "# TODO: もう一度、君を実装する。"
    ]
    return title, lines

# 03 砂時計のfor
def poem_03():
    title = "砂時計のfor"
    grains = ["砂"] * 7
    tick = []
    for i, g in enumerate(grains, 1):
        tick.append(f"{i:02d} {g}")
    lines = ["for 粒 in 砂時計:", *tick, "時間は可迭代、恋は片方向。"]
    return title, lines

# 04 ハッシュの祈り
def poem_04():
    title = "ハッシュの祈り"
    msg = "薔薇/君/夜"
    h = hashlib.sha256(msg.encode()).hexdigest()[:16]
    lines = [
        f"sha256('{msg}') → {h}",
        "誰にも改竄できない祈りを、",
        "わたしの舌下に封印する。"
    ]
    return title, lines

# 05 無限列車はyieldする
def poem_05():
    title = "無限列車はyieldする"
    def petals():
        while True:
            yield "花弁"
    gen = petals()
    lines = ["next(gen) × 5 → " + " ".join(next(gen) for _ in range(5)),
             "止められるのは意志だけ、breakは自由意志の名前。"]
    return title, lines

# 06 偏微分の恋
def poem_06():
    title = "偏微分の恋"
    def f(x, y): return x**2 + y**2
    x, y = 3, 4
    dx = f(x+1e-6,y)-f(x,y)
    dy = f(x,y+1e-6)-f(x,y)
    lines = [
        f"∂f/∂x≈{dx/1e-6:.3f}, ∂f/∂y≈{dy/1e-6:.3f}",
        "傾きは触れたい欲望、",
        "原点に戻れば君の名が0でないと知る。"
    ]
    return title, lines

# 07 True は 1
def poem_07():
    title = "True は 1"
    t = True + True + False
    lines = [f"True+True+False = {t}",
             "算術が証言する微かな肯定、",
             "わたしは足し合わせるたび、光った。"]
    return title, lines

# 08 乱数の宿命
def poem_08():
    title = "乱数の宿命"
    random.seed(8)
    nums = [str(random.randint(0,9)) for _ in range(8)]
    lines = ["seed(8) → " + "".join(nums),
             "宿命でさえ、初期化でやり直せると",
             "わたしにだけ耳打ちする夜。"]
    return title, lines

# 09 ターミナルの薔薇
def poem_09():
    title = "ターミナルの薔薇"
    rose = ["  @", " @@@", "@@@@@", " @@@", "  @"]
    lines = ["print(rose) →"] + rose + ["等幅の赤に、指が震える。"]
    return title, lines

# 10 mapは遠雷
def poem_10():
    title = "mapは遠雷"
    word = list(map(lambda c: f"{c}*", "恋"))
    lines = ["map(恋) → " + "".join(word), "遠雷のように伸びる尾音。"]
    return title, lines

# 11 setで重複を捨てる
def poem_11():
    title = "setで重複を捨てる"
    bag = list("さよならならなら")
    s = "".join(sorted(set(bag), key=bag.index))
    lines = ["袋: " + "".join(bag), "set→ " + s, "残った音節だけが真実だ。"]
    return title, lines

# 12 zipで手をつなぐ
def poem_12():
    title = "zipで手をつなぐ"= "わたし"= "あなた"
    joined = " ".join(a+b for a,b in zip(,))
    lines = ["zip(わたし,あなた) → " + joined, "足りない指は余白で埋めた。"]
    return title, lines

# 13 rangeの遠近法
def poem_13():
    title = "rangeの遠近法"
    steps = "→".join(str(i) for i in range(5, -1, -1))
    lines = [steps, "カウントダウンの背で薔薇が開く。"]
    return title, lines

# 14 datetimeの墓標
def poem_14():
    title = "datetimeの墓標"
    today = dt.date.today().isoformat()
    lines = [f"today() → {today}", "生の刻印は、墓標の初稿である。"]
    return title, lines

# 15 anyとall
def poem_15():
    title = "anyとall"
    vows = [True, True, False]
    lines = [f"any(vows)={any(vows)}, all(vows)={all(vows)}",
             "一つの灯で十分、永遠は複数形を要求する。"]
    return title, lines

# 16 リスト内包の睡蓮
def poem_16():
    title = "リスト内包の睡蓮"
    pond = ["睡蓮" if i%2 else "影" for i in range(6)]
    lines = ["[" + ", ".join(pond) + "]", "偶数に咲く、奇数に沈む。"]
    return title, lines

# 17 スタックの夢
def poem_17():
    title = "スタックの夢"
    stack = []
    for s in ["夜","指","薔薇","熱"]:
        stack.append(s)
    popped = "→".join(reversed(stack))
    lines = ["push×4; pop* → " + popped, "最後に積んだ嘘からほどけていく。"]
    return title, lines

# 18 再帰で名を呼ぶ
def poem_18():
    title = "再帰で名を呼ぶ"
    def call(n):
        return "君" if n<=1 else call(n-1)+"、君"
    lines = [call(4), "停止条件=赦し。"]
    return title, lines

# 19 complexの血色
def poem_19():
    title = "complexの血色"
    z = 3+4j
    r = abs(z)
    lines = [f"z=3+4j → |z|={r}", "虚部を抱いて現実が立つ。"]
    return title, lines

# 20 enumerateの手帳
def poem_20():
    title = "enumerateの手帳"
    memo = ["薔薇の名","合図","別れ"]
    lines = [", ".join(f"{i}:{v}" for i,v in enumerate(memo,1)),
             "番号が悲しみを整列させる。"]
    return title, lines

# 21 filterの雪
def poem_21():
    title = "filterの雪"
    chars = "かなしみ"
    vowels = set("あいうえお")
    s = "".join(filter(lambda c: c in vowels, chars))
    lines = [f"{chars} → 母音: {s}", "雪だけが積もっていく。"]
    return title, lines

# 22 min/maxの双極
def poem_22():
    title = "min/maxの双極"
    arr = [3,-1,0,5,-2]
    lines = [f"min={min(arr)}, max={max(arr)}",
             "振り切れた両端にだけ、真夜中が棲む。"]
    return title, lines

# 23 roundの口づけ
def poem_23():
    title = "roundの口づけ"
    pi = round(math.pi, 3)
    lines = [f"π≈{pi}", "円環の誓いを、小数点で刻む。"]
    return title, lines

# 24 joinの縫合
def poem_24():
    title = "joinの縫合"
    parts = ["傷","と","傷"]
    lines = ["'•'.join → " + "•".join(parts),
             "点で縫い合わせた夜は、ほどけにくい。"]
    return title, lines

# 25 sortedの葬列
def poem_25():
    title = "sortedの葬列"
    names = ["蘭","薔薇","茉莉","椿"]
    lines = ["sorted → " + "→".join(sorted(names)),
             "順番が決まると、涙は行進になる。"]
    return title, lines

# 26 powの祈祷
def poem_26():
    title = "powの祈祷"
    lines = [f"pow(闇,2,希望) の定義だけを知っている。",
             "剰余でやっと、朝に触れる。"]
    return title, lines

# 27 divmodの別離
def poem_27():
    title = "divmodの別離"
    q, r = divmod(17, 5)
    lines = [f"divmod(17,5) → 商={q}, 余={r}",
             "割り切れないからこそ、君は残る。"]
    return title, lines

# 28 itertools.cycleの回廊
def poem_28():
    title = "cycleの回廊"
    cyc = it.cycle("薔薇")
    lines = ["".join(next(cyc) for _ in range(12)),
             "繰り返しは呪いであり、子守歌でもある。"]
    return title, lines

# 29 statistics の中央値
def poem_29():
    title = "中央値という温度"
    xs = [36.0, 36.5, 38.9, 35.8, 37.1]
    lines = [f"median → {stats.median(xs)}",
             "極端を捨てて残る温度が、わたしたちの平和。"]
    return title, lines

# 30 formatの鏡
def poem_30():
    title = "formatの鏡"
    lines = ["{:>8}".format("君"), "{:<8}".format("わたし"), "左右対称でやっと対話になる。"]
    return title, lines

# 31 f-stringの血
def poem_31():
    title = "f-stringの血",= "君", "私"
    lines = [f"{}{} = {}の欠損", f"{}{} = {}の過剰", "等式がいちばん痛い。"]
    return title, lines

# 32 sliceの刃
def poem_32():
    title = "sliceの刃"
    s = "薔薇言語"
    lines = [f"{s}[::-1] → {s[::-1]}", "逆さにしても香る名は、本物だ。"]
    return title, lines

# 33 dictの地図
def poem_33():
    title = "dictの地図"
    d = {"出会い":1,"口づけ":2,"沈黙":3}
    lines = [", ".join(f"{k}:{v}" for k,v in d.items()),
             "キーを失くしたら、帰れない。"]
    return title, lines

# 34 with の祈り
def poem_34():
    title = "with の祈り"
    lines = ["with 目を閉じる() as 夜:",
             "    すべての資源を闇へ返す。",
             "安全に手放せたときだけ、朝は来る。"]
    return title, lines

# 35 boolの詩学
def poem_35():
    title = "boolの詩学"
    lines = [f"bool('')={bool('')}, bool('愛')={bool('愛')}",
             "空文字の沈黙、非空の鼓動。"]
    return title, lines

# 36 sumの子守歌
def poem_36():
    title = "sumの子守歌"
    xs = [1,1,2,3,5,8]
    lines = [f"sum({xs})={sum(xs)}",
             "眠れない夜は、数列が抱いてくれる。"]
    return title, lines

# 37 printの遺言
def poem_37():
    title = "printの遺言"
    lines = ['print("さようなら、世界")',
             "出力は一度きり、入力は戻らない。"]
    return title, lines

# 38 absの赦し
def poem_38():
    title = "absの赦し"
    x = -7
    lines = [f"abs({x})={abs(x)}", "負号を外すだけで、泣きやめる数がある。"]
    return title, lines

# 39 chrとord
def poem_39():
    title = "chrとord"
    c = '薔'
    lines = [f"ord('{c}')={ord(c)} → chr=同じ薔",
             "数に還っても、香りは消えない。"]
    return title, lines

# 40 None合流点
def poem_40():
    title = "None合流点"
    a = None or "君"
    b = None or "わたし"
    lines = [f"a={a}, b={b}", "空を通って、ようやく出会う。"]
    return title, lines

# 41 タプルの静物
def poem_41():
    title = "タプルの静物"
    t = ("花瓶","薔薇","水")
    lines = [str(t), "変更不能、つまり永遠。"]
    return title, lines

# 42 try/elseの晴天
def poem_42():
    title = "try/elseの晴天"
    lines = []
    try:
        1/1
    except ZeroDivisionError:
        lines.append("雨が続く。")
    else:
        lines.append("雲が裂け、分母は青い。")
    return "try/elseの晴天", lines

# 43 whileの祈祷書
def poem_43():
    title = "whileの祈祷書"
    n, out = 3, []
    while n:
        out.append("アーメン")
        n -= 1
    lines = [" ".join(out), "同じ言葉で、違う痛みが薄まる。"]
    return title, lines

# 44 文字幅という運命
def poem_44():
    title = "文字幅という運命"
    s = "薔薇"
    lines = [f"len('{s}')={len(s)} (bytes={len(s.encode())})",
             "人の数え方で、重さは変わる。"]
    return title, lines

# 45 エスケープの窓
def poem_45():
    title = "エスケープの窓"
    lines = [r"\"に続く夜を、\\で逃げる。",
             r"文字列の中だけ、自由に雨宿り。"]
    return title, lines

# 46 from __future__ import 君
def poem_46():
    title = "from __future__ import 君"
    year = dt.date.today().year + 1
    lines = [f"来年({year})から来た光で、",
             "現在をコンパイルする。"]
    return title, lines

# 47 ヒアドキュメントの夢
def poem_47():
    title = "ヒアドキュメントの夢"
    poem = textwrap.dedent("""\
        '''薔薇はsleepし、コンソールは息を潜める。
        三連クォートの洞窟で、
        回音だけが真実を反復する。'''""")
    return title, [poem]

# 48 list.reverse の転回
def poem_48():
    title = "reverse の転回"
    xs = ["出会い","接吻","沈黙","別れ"]
    xs.reverse()
    lines = ["→".join(xs), "物語は、いつでも巻き戻せる気がした。"]
    return title, lines

# 49 next の境界
def poem_49():
    title = "next の境界"
    g = (c for c in "永遠")
    a = next(g); b = next(g)
    lines = [f"next→ {a} {b} …", "先取りした時間だけが、手の内にある。"]
    return title, lines

# 50 exit()
def poem_50():
    title = "exit()"
    lines = ["プログラムが静かに終わるとき、",
             "画面の黒は、夜のやさしい別名になる。"]
    return title, lines

POEMS = [
    poem_01, poem_02, poem_03, poem_04, poem_05, poem_06, poem_07, poem_08, poem_09, poem_10,
    poem_11, poem_12, poem_13, poem_14, poem_15, poem_16, poem_17, poem_18, poem_19, poem_20,
    poem_21, poem_22, poem_23, poem_24, poem_25, poem_26, poem_27, poem_28, poem_29, poem_30,
    poem_31, poem_32, poem_33, poem_34, poem_35, poem_36, poem_37, poem_38, poem_39, poem_40,
    poem_41, poem_42, poem_43, poem_44, poem_45, poem_46, poem_47, poem_48, poem_49, poem_50,
]

if __name__ == "__main__":
    print("『薔薇言語』動くコード詩集\n")
    for i, f in enumerate(POEMS, 1):
        title, lines = f()
        show(i, title, lines)
    print(LINE)
    print("end.")

Discussion