using System; using System.Collections.Generic; using System.Linq; using System.Text; // The Little Schemer // chapter 4 // ISBN:0262560992 namespace NumbersGames { class Program { static void Main(string[] args) { /* 再帰で加減乗除(四足演算) */ //インクリメント var inc = new Func<int, int>(n => ++n); Console.WriteLine("inc(1) -> {0}", inc(1));// -> 2 //デクリメント var dec = new Func<int, int>(n => --n); Console.WriteLine("dec(1) -> {0}", dec(1));// -> 0 //加算 Func<int, int, int> add = null; add = (n, m) => { return m == 0 ? n : inc(add(n, dec(m))); }; Console.WriteLine("add(2, 3) -> {0}", add(2, 3));// -> 5 //減算 Func<int, int, int> sub = null; sub = (n, m) => { return m == 0 ? n : dec(sub(n, dec(m))); }; Console.WriteLine("sub(3, 2) -> {0}", sub(3, 2));// -> 1 //大なり Func<int, int, bool> bgr = null; bgr = (n, m) => { return n == 0 ? false : m == 0 ? true : bgr(dec(n), dec(m)); }; Console.WriteLine("bgr(3, 2) -> {0}", bgr(3, 2));// -> True //小なり Func<int, int, bool> sml = null; sml = (n, m) => { return m == 0 ? false : n == 0 ? true : sml(dec(n), dec(m)); }; Console.WriteLine("sml(2, 3) -> {0}", sml(2, 3));// -> True //乗算 Func<int, int, int> mul = null; mul = (n, m) => { return m == 0 ? m : add(n, mul(n, dec(m))); }; Console.WriteLine("mul(2, 3) -> {0}", mul(2, 3));// -> 6 //除算 Func<int, int, int> div = null; div = (n, m) => { return sml(n, m) ? 0 : inc(div(sub(n, m), m)); }; Console.WriteLine("div(15, 3) -> {0}", div(15, 3));// -> 5 Console.ReadLine(); } } } |
0 件のコメント:
コメントを投稿