-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListDemo.cs
More file actions
60 lines (51 loc) · 2.02 KB
/
Copy pathListDemo.cs
File metadata and controls
60 lines (51 loc) · 2.02 KB
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
57
58
59
60
using System;
using System.Diagnostics;
namespace MondadsInCsharp.Demos
{
public static class ListDemo
{
public static void PrintAll<T>(SList<T> list)
{
for (var prev = list; prev is Cons<T> el; prev = el.Tail)
{
Console.WriteLine(el.Head.ToString());
}
}
public static SList<int> Double(SList<int> list)
{
return list.fmap(x => x + 1);
}
public static SList<string> ToWord(SList<int> list)
{
var words = new[] {"one", "two", "three", "four"};
return list.fmap(x => x >= 0 && x < words.Length ? words[x] : "unknown number");
}
public static void CheckRightAssociativity()
{
var input = new Cons<int>(1, new Cons<int>(2, new Cons<int>(3, new Empty<int>())));
var output = input.bind(x => x.pureSList());
Debug.Assert(input == output);
}
public static SList<T> filter<T>(this SList<T> list, Func<T, bool> predicate)
=> list.bind(x => predicate(x) ? x.pureSList() : new Empty<T>());
public static SList<(T,T)> cartesianProduct<T>(SList<T> one, SList<T> two)
{
return one.bind(x => two.bind(y => new Cons<(T, T)>((x, y), new Empty<(T, T)>())));
}
public static SList<TOut> listComprension<TIn, TOut>(this SList<TIn> list, Func<TIn, TOut> mapping,
Func<TIn, bool> predicate)
=> list.bind(x =>
{
if (predicate(x))
return new Cons<TOut>(mapping(x), new Empty<TOut>()) as SList<TOut>;
return new Empty<TOut>();
});
public static SList<(T1, T2)> zip<T1, T2>(SList<T1> one, SList<T2> two)
{
Func<T1, Func<T2, (T1, T2)>> mkTuple = x => y => (x, y);
return mkTuple.fmap(one).ab(two);
}
public static SList<int> sumLists(SList<int> one, SList<int> two)
=> zip(one, two).fmap(t => t.Item1 + t.Item2);
}
}