首页 > 其他 > 详细

函数式数据结构-列表

时间:2021-01-12 09:48:51      阅读:33      评论:0      收藏:0      [点我收藏+]

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

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);

 


 

 

技术分享图片

 

函数式数据结构-列表

原文:https://www.cnblogs.com/xtt321/p/14265247.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!