函数式数据结构-列表

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

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

2、函数式编程的优势:

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

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

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

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

 

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

 

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

 

1 FList<int> list1 = FList<int>.Empty;
2 FList<int> list2 = list1.Cons(1).Cons(2).Cons(3);

 


 

 

 

posted @   温暖如太阳  阅读(276)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示