9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

D言語でHello, World!を書いてみる

Last updated at Posted at 2025-12-02

以下のソースコードがD言語のHello, World!です。

import std.stdio;

void main()
{
    writeln("Hello, world!");
}

D言語はC言語やC++言語から影響を受けているため、C言語っぽさのある文法です。
これだけで終わるともったいないので、D言語の機能をいくつか紹介します。

D言語にはUniform Function Call Syntax(UFCS)という機能があります。
これは、オブジェクト指向のメソッド呼び出しのような見た目で関数を呼び出すことができる機能です。
f(a, b, c) という関数呼び出しを、 a.f(b, c) と書くことができます。
この構文を見て、NimやElixerを思い出す人もいるようですが、個人的にはPythonのselfを真っ先に思い出しました。
この構文のお陰で、関数呼び出しが連続する場合でも括弧の入れ子を抑えられ、また実際に関数が呼び出される順番とソースコードに関数を書く順番を近づけることもできます。

f1(f2(f3(a)))
↓
a.f3().f2().f1()

更に、D言語にはCompile-Time Function Execution(CTFE)という機能もあります。
その名の通り、コンパイル時に関数の実行を行い、実行時には計算済みの値を使う機能です。
この機能はとても便利ですが、大いなる力には、大いなる責任が伴う という言葉が表す通り、間違った使い方をすると魔境のようなHello Worldを書くこともできます。
最後にアンサイクロペディアに掲載されているHello World!を紹介します。

import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.string;

struct D
{
    string msg;

    D opDispatch(string s)()
    {
		return typeof(return)(
			((a, b)=>a.equal(b))(
				msg.retro.cycle.take(2),
				chain(msg, s).retro.take(2).array.retro)
				? ((a, b)=>(a.insertInPlace(msg.countUntil(b)+1, ", "), a.idup))
					(msg.dup, msg.retro.take(2).array.retro) ~ s
				: text(msg,s));
    }

    string d(T)()
    {
        return text(msg, T.stringof.toLower, "! ", T.stringof);
    }
}

struct H
{
    static enum opDispatch(string s) = D(typeof(this).stringof ~ s);
}

pragma(msg, H.e.l.l.o. w.o.r.l.d! D);

Ref:
https://ja.uncyclopedia.info/wiki/D%E8%A8%80%E8%AA%9E

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?