Skip to content

Instantly share code, notes, and snippets.

@namachan10777
Last active November 22, 2017 13:09
Show Gist options
  • Save namachan10777/19207b59d4d60ea2944684f04bb6331c to your computer and use it in GitHub Desktop.
Save namachan10777/19207b59d4d60ea2944684f04bb6331c to your computer and use it in GitHub Desktop.
//リストの長さNを型に埋め込む
struct SList(T, alias N) {
T[] arr;
}
//空リスト
auto nil(T)() {
SList!(T, 0) sl;
return sl;
}
//要素の追加
auto cons(SL : SList!(T, N), T, alias N)(SL l, T val) {
return SList!(T, N+1)(l.arr ~ val);
}
//先頭要素の取得
auto hd(SL : SList!(T, N), T, alias N)(SL l) {
static assert (N != 0, "list is empty!");
return l.arr[$-1];
}
//先頭を取り除いたリスト
auto tl(SL : SList!(T, N), T, alias N)(SL l) {
static assert (N != 0, "list is empty!");
return SList!(T, N-1)(l.arr[0..$-2]);
}
//リストの連結
auto app(SL1 : SList!(T, N1), SL2 : SList!(T, N2), T, alias N1, alias N2)(SL1 l1, SL2 l2) {
return SList!(T, N1+N2)(l1.arr ~ l2.arr);
}
//インデックスアクセス
auto idx(alias Idx, SL : SList!(T, N), T, alias N)(SL l) {
static assert (N > 0 && Idx < N, "out of range");
return l.arr[Idx];
}
void main() {
//[1,2]
auto sl1 = nil!int.cons(1).cons(2);
assert (sl1.hd == 2);
assert (sl1.tl.hd == 1);
//assert (sl1.tl.tl.hd == 1); //compile error
auto sl2 = nil!int.cons(3);
//[1,2] ~ [3]
auto sl3 = sl1.app(sl2);
assert (sl3.hd == 3);
//assert (sl3.tl.tl.tl.hd == 3); //compile error
assert (sl3.idx!1 == 2);
//assert (sl3.idx!4 == 2); //compile error
}
@namachan10777
Copy link
Author

楽しい✌('ω'✌ )三✌('ω')✌三( ✌'ω')✌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment