函数式数据结构-列表


在开始之前我们先了解几个名词:

1、什么是函数式编程:函数式编程属于"结构化编程"的一种,主要思想是把运算过程尽量写成一系列嵌套的函数调用,可以说是面向过程的程序设计。

2、函数式编程的优势:

  • 1)函数式编程大量使用函数,减少了代码的重复,因此程序比较短,开发速度较快。

  • 2)易于"并发编程" 。

  • 3)函数式编程不依赖、也不会改变外界的状态,只要给定输入参数,返回的结果必定相同。

3、什么是函数式数据结构:函数式数据结构只能被纯函数操作,纯函数一定不能修改原始数据结构或者产生副作用。函数式数据结构被定义为不可变的。

列表是由两个链接元素组成的递归数据结构:头部与尾部。

 1     /// 
 2     /// 函数式列表
 3     /// 
 4     /// 
 5     public sealed class FList
 6     {
 7         public T Head { get; }
 8 
 9         public FList Tail { get; }
10 
11         public bool IsEmpty { get; }
12 
13         private FList(T head, FList tail)
14         {
15             Head = head;
16             Tail = tail.IsEmpty? FList.Empty:tail;
17             IsEmpty = false;
18         }
19 
20         private FList()
21         {
22             IsEmpty = true;
23         }
24 
25         public static FList Cons(T head, FList tail)
26         {
27             return tail.IsEmpty ? new FList(head, Empty) : new FList(head, tail);
28         }
29 
30         public FList Cons(T element)
31         {
32             return FList.Cons(element, this);
33         }
34 
35         public static readonly FList Empty = new FList();
36     }
1 FList<int> list1 = FList<int>.Empty;
2 FList<int> list2 = list1.Cons(1).Cons(2).Cons(3);