language: C# (mono-2.8)
date: 666 days 23 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Linq;
using System.Collections.Generic;
 
delegate bool OutFunc<T>(string input, out T value);
 
static class Program
{
    static void Main(string[] args)
    {
        var input = "123";
        var r = input.ParseOrDefault(-1, int.TryParse);
        Console.WriteLine(r);
    }
 
    // 特化的に組み合わせたメソッド
    static T ParseOrDefault<T>(this string input, T defaultValue, OutFunc<T> tryParse)
    {
        return Return(input)
            .Select(s => TryParse(s, tryParse))
            .Select(t => t.Item1 ? t.Item2 : defaultValue)
            .First();
    }
 
    // 汎用的に使えるパーツ群
    static IEnumerable<T> Return<T>(T value)
    {
        yield return value;
    }
 
    static Tuple<bool, T> TryParse<T>(string input, OutFunc<T> tryParse)
    {
        T value;
        return Tuple.Create(tryParse(input, out value), value);
    }
}
 
static class Tuple
{
    public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
    {
        return new Tuple<T1, T2>(item1, item2);
    }
}
 
class Tuple<T1, T2>
{
    public readonly T1 Item1;
    public readonly T2 Item2;
 
    public Tuple(T1 item1, T2 item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}