構造体を定義すると Equals が自動的に実装されるが、IEquatable<T> を実装した方がよい

方法: 型の値の等価性を定義する (C# プログラミング ガイド) | Microsoft Docs より: 構造体を定義すると、System.Object.Equals(Object) メソッドの System.ValueType オーバーライドから継承された値の等価性が既定で実装されます。 この実装では、リフレ…

Mono 5.0 と C# 7 の Local Functions, Tuples で遊ぶ

Mono 5.0 と C# 7 で遊びます。 Mono 5.0.0 Release Notes | Mono まずは、mono のアップグレード。 $ brew upgrade mono mono のバージョンの確認。 $ mono --version Mono JIT compiler version 5.0.1.1 (2017-02/5077205 Wed May 31 14:47:54 BST 2017) C…

算術シフト、論理シフト

using System; class Program { static void Display(int n) { Console.WriteLine(" int {0,12} {1,32}", n, Convert.ToString(n, 2)); } static void Display(uint n) { Console.WriteLine("uint {0,12} {1,32}", n, Convert.ToString(n, 2)); } static voi…

関数から整数(int)を 2 つ返すとき、配列とタプルの速度差を調べる

int の配列を new するのと、タプルを生成するのとで速度に差が出るのか計測してみました。 using System; using System.Diagnostics; class Program { static int[] CreateArray(int a, int b) { return new[] { a, b }; } static Tuple<int, int> CreateTuple(int a,</int,>…

0 と 1 を交互に繰り返したいときは xor を使う

変数に格納されている整数値が、 0 のときは 1 を返す 1 のときは 0 を返す というように 0 と 1 を交互に繰り返したいときは、1 と xor するとできます。 $ csharp Mono C# Shell, type "help;" for help Enter statements below. csharp> int a = 0; cshar…

文字列リテラルにダブルクォートを含める

文字列リテラルにダブルクォートを含めるには、次のようにします。 標準の文字列リテラルなら、バックスラッシュでエスケープします 逐語的文字列リテラルなら、ダブルクォートを 2 つ重ねます using System; class Program { static void Main() { Console.…

IEnumerable, IEnumerator

GetEnumerator() を定義すると、foreach でループを回すことができます。 using System; using System.Collections; using System.Collections.Generic; class Program { static IEnumerable<int> G() { yield return 1; yield return 2; } static IEnumerator<int> T(</int></int>…

プロパティでコルーチン

プロパティでコルーチンを定義するサンプルです。 using System; using System.Collections.Generic; using System.Linq; class Test { public IEnumerable<int> G { get { int n = 0; while (true) { yield return n++; } } } } class Program { static void Mai</int>…

速度のために List クラスに Last 拡張メソッドを定義しようとしたけど要らなかった

やろうとしたこと List<T> の最後の要素を取得するメソッドが欲しい Enumerable.Last メソッドがある だけど、シーケンスを辿るので O(N) で遅いのでは? 先に結論から言うと、IList<T> インターフェース を実装しているなら、 Enumerable.Last は O(N) ではなく O</t></t>…

タプルを == 演算子で比較、Equals() で比較

using System; class Program { static void Main() { var a = Tuple.Create(1, 2); var b = Tuple.Create(1, 2); Console.WriteLine(a == b); // False Console.WriteLine(a.Equals(b)); // True } } 実行結果です。 False True タプルを Dictionary のキー…

2 つの Dictionary をひとつにまとめる

両方の Dictionary に同じキーが含まれる場合は、Sum() で足し合わせます。 using System; using System.Collections.Generic; using System.Linq; class Program { static Dictionary<int, int> Add(Dictionary<int, int> a, Dictionary<int, int> b) { return a.Concat(b).GroupBy(e => e</int,></int,></int,>…

0,1,0,1,0,1... を繰り返すシーケンス

using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> ZeroOne() { int n = 0; while (true) { yield return n; n ^= 1; } } static void Main() { Console.WriteLine(string.Join(",", ZeroOne().Take(</int>…

Pairs 関数

Python の >>> [(i, j) for i in range(3) for j in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] のような各ペアを求める Pairs 関数を作成してみました。 using System; using System.Collections.Generic; using…

Array.Clear() で 2 次元配列をクリアする

Array.Clear メソッドは、1 次元配列だけでなく、2 次元配列もクリアすることが出来ます。 using System; using System.Collections.Generic; using System.Linq; class Program { static void Display(int[,] ary) { for (int i = 0; i < ary.GetLength(0);…

Conditional 属性の練習

using System; using System.Diagnostics; class Program { [Conditional("TEST")] static void Foo() { Console.WriteLine("FOO!"); } static void Main() { Console.WriteLine("BEGIN"); Foo(); Console.WriteLine("END"); } } 実行結果です。 $ mcs -defi…

Type からインスタンスを生成する

using System; class Foo { public void Say() { Console.WriteLine("Foo!"); } } class Bar { public Bar(int n, string s) { Console.WriteLine("n:{0} s:{1}", n, s); } public void Say() { Console.WriteLine("Bar!"); } } class Program { static void…

SEND + MORE = MONEY

using System; using System.Collections.Generic; using System.Linq; class Program { static int ToInt(string s, int[] map) { int x = 0; foreach (var c in s) { x = 10 * x + map[c]; if (x == 0 && s.Length > 1) return -1; // leading zero } retu…

文字列の配列を文字のシーケンスに変換する

using System; using System.Linq; class Program { static void Main() { var ss = new[] { "foo", "bar", "baz" }; // 文字列の配列を文字のシーケンスにする var cs = ss.SelectMany(e => e); Console.WriteLine(string.Join(" ", cs)); // => f o o b a …

Frequencies メソッドを作る

シーケンスに含まれる要素の出現回数を求める Frequencies メソッドを作ってみました。 using System; using System.Collections.Generic; using System.Linq; static class Ext { public static Dictionary<T, int> Frequencies<T>(this IEnumerable<T> xs) { var d = new</t></t></t,>…

CompositeDisposable クラスの Dispose メソッドを呼び出した後に Add したときの振る舞い

CompositeDisposable クラスの Dispose メソッドを呼び出すと、CompositeDisposable に格納されている全ての要素に対して Dispose メソッドが呼ばれます。 CompositeDisposable クラスの Dispose メソッドを呼び出すと、IsDisposed プロパティは true となり…

Butlast メソッド

シーケンスの最後の要素を取り除く Butlast メソッドを作ってみました。 using System; using System.Collections.Generic; using System.Linq; public static class Ext { public static IEnumerable<T> Butlast<T>(this IEnumerable<T> xs) { bool first = true; T </t></t></t>…

Iterate メソッド

初期値と「次の値」を返す関数を引数で受け取り、無限シーケンスを返す Iterate メソッドを作ってみました。 using System; using System.Collections.Generic; using System.Linq; class Iter { public static IEnumerable<T> Iterate<T>(T init, Func<T, T> next) { T </t,></t></t>…

MinBy, MaxBy を作る

using System; using System.Collections.Generic; using System.Linq; public static class Ext { public static T MinBy<T, U>(this IEnumerable<T> xs, Func<T, U> key) where U : IComparable<U> { return xs.Aggregate((a, b) => key(a).CompareTo(key(b)) < 0 ? a : b); </u></t,></t></t,>…

比較関数を渡せる GroupBy メソッドを作る

比較関数を渡せる GroupBy メソッドを作ってみました。 using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<T[]> GroupBy<T>(IEnumerable<T> xs, Func<T, T, bool> match) { var ls = new List<T>(); foreach (var x in xs) { if</t></t,></t></t></t[]>…

1 次元配列の回転

1 次元配列を回転するサンプルです。 using System; using System.Collections.Generic; using System.Linq; class Program { static T[] Rotate<T>(T[] xs, int n) { var ret = new T[xs.Length]; if (ret.Length == 0) return ret; int m = n % ret.Length; f</t>…

インスタンスが null の場合でも拡張メソッドの呼び出しは可能

インスタンスが null の場合にメソッド呼び出しを行うと、System.NullReferenceException 例外が生成されますが、拡張メソッドの場合は、インスタンスが null でも呼び出しが可能です。 using System; public class Foo { public void Hello() { Console.Wri…

Partition 関数

シーケンスの要素を、述語関数を満たす要素と満たさない要素に分割する Partition 関数(メソッド)を作ってみました。 using System; using System.Collections.Generic; using System.Linq; class Program { static Tuple<List<T>, List<T>> Partition<T>(IEnumerable<T> xs, </t></t></t></list<t>…

Group 関数

シーケンス内の隣り合う要素のうち、同じ値のものを配列にまとめる関数 Group を作ってみました。 using System; using System.Collections.Generic; using System.Linq; static class Iter { public static IEnumerable<T[]> Group<T>(IEnumerable<T> xs) { var ls = n</t></t></t[]>…

対角線のどちら側か

R, C が与えられたとき、それぞれの格子点が対角線のどちら側にあるか判定するプログラムです。 対角線の傾き (R-1)/(C - 1) 格子点の傾き i/j について、その大きさを比較します。もし傾きが等しければ格子点は対角線上にあることがわかります。 等しくなけ…

ラムダ式で再帰

ラムダ式の再帰呼び出しのサンプルです。 using System; class Program { static void Main() { Func<int, int> fact = null; fact = n => { if (n == 0) return 1; else return n * fact(n - 1); }; for (int i = 1; i < 10; i++) Console.WriteLine(fact(i)); } } 実</int,>…