作为一个haskell这门函数式编程语言的爱好者,我特别喜欢它的list操作和推导功能。与传统面向对象或者过程语言不同的是,函数式语言通常喜欢把它们分为head、tail或者init、last等两部分,而不是一个数组性的列表。

针对列表的操作,也通常使用递归和迭代的方式来完成,特别强大。java8后,有了stream之后,才感觉能够和它有得一拼,但总感觉stream操作的list比较繁琐。

工作之余,做为一种爱好或者锻炼,我自己用java实现了一套haskell-style的list类,支持大部分原生haskell list函数和操作,并且可以与java list(准确来说是迭代器)进行相互转换。

得到一个haskell-style列表,你仅仅需要像这样:

PreludeList<Integer> intList = PreludeList.of(1,2,3,4);

你还可以像下面这样,得到一个无限长的列表:

PreludeList<Integer> rangeList = PreludeList.range(1, 10000);
PreludeList<Integer> repeatList = PreludeList.repeat(3);
PreludeList<Integer> cycleList = PreludeList.cycle(Preludelist.of(1,3,5));
PreludeList<Integer> iterableList = PreludeList.iterable(t -> t * 3, 3); //[3, 9, 27, 81....]

并且,这些全部都是惰性求值,真正用的时候才会去延迟计算。

你还可以进行更多的list操作:

PreludeList<Integer> intList = PreludeList.of(1,2,3,4,5,6);

//基础操作
Integer headValue = PreludeList.head(intList);
PreludeList<Integer> tailList = PreludeList.tail(intList);
PreludeList<Integer> initList = PreludeList.init(intList);
Integer lastValue = PreludeList.last(intList); //列表操作
PreludeList<Integer> revertList = PreludeList.reverse(intList); //一个反转的整数列表
PreludeList<Integer> take3List = PreludeList.take(3, intList); //取前面三项组成一个新的列表
PreludeList<Integer> drop3List = PreludeList.drop(3, intList); //移除掉前面三项组成的新列表
PreludeList<Integer> filterList = PreludeList.filter(t -> t % 2 == 0, intList); //取偶数组成新列表
PreludeList<Integer> mapList = PreludeList.map(t -> t * 2, intList); //每个数增长到2倍的新列表 //与Java迭代器的互动
Iterable iterable = PreludeList.to(intList);
PreludeList<Integer> iterableList = PreludeList.from(iterable); //其他
System.out.println(intList.toString()); //它会输出[1,2,3,4,5,6]

说了这么多,有没有点期待,完整的功能比上面更丰富,还在不断完善中。。。。。

代码见下:

import javax.swing.text.html.HTMLDocument;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Predicate; /**
*
* @author richardyang
* @version $Id: PreludeList.java, v 0.1 2018年06月01日 下午5:10 richardyang Exp $
*/
public class PreludeList<T> { private static class Nil<T> extends PreludeList<T> {
@Override
protected T getHead() {
throw new UnsupportedOperationException("Prelude list empty");
} @Override
protected PreludeList<T> getTail() {
throw new UnsupportedOperationException("Prelude list empty");
}
} private static class RepeatList<T> extends PreludeList<T> {
private T x; protected RepeatList(T x) {
this.isEmpty = false;
this.x = x;
} @Override
protected T getHead() {
return x;
} @Override
protected PreludeList<T> getTail() {
return new RepeatList(x);
}
} private static class CycleList<T> extends PreludeList<T> {
private PreludeList<T> cycleList; protected CycleList(PreludeList<T> list) {
this.cycleList = list;
this.isEmpty = false;
} @Override
protected T getHead() {
return cycleList.getHead();
} @Override
protected PreludeList<T> getTail() {
if (!nil(cycleList.getTail())) {
PreludeList<T> tailList = cycleList.getTail();
return PreludeList.cons(tailList, new CycleList<T>(cycleList));
} return new RepeatList<T>(head(cycleList));
}
} private static class IterateList<T> extends PreludeList<T> {
private Function<T, T> function;
private T x; protected IterateList(Function<T, T> function, T x) {
this.function = function;
this.x = x;
this.isEmpty = false;
} @Override
protected T getHead() {
return x;
} @Override
protected PreludeList<T> getTail() {
return new IterateList<T>(function, function.apply(x));
}
} private static class RangeList<T extends Number> extends PreludeList<T> {
private T start;
private T stop;
private T step;
private int stepCount; protected RangeList(T start, T stop, T step, int stepCount) {
this.start = start;
this.stop = stop;
this.step = step;
this.stepCount = stepCount;
this.isEmpty = false;
} @Override
protected T getHead() {
try {
Number result = NumberFormat.getInstance().parse(String.valueOf(start.doubleValue() + step.doubleValue() * stepCount));
return (T)result;
} catch (ParseException e) {
e.printStackTrace();
} return null;
} @Override
protected PreludeList<T> getTail() {
if (canNext()) {
return new RangeList<T>(start, stop, step, stepCount + 1);
} return nilElem;
} private boolean canNext() {
boolean lt = step.doubleValue() > 0;
return lt
? start.doubleValue() + step.doubleValue() * (stepCount + 1) <= stop.doubleValue()
: start.doubleValue() + step.doubleValue() * (stepCount + 1) >= stop.doubleValue();
}
} private static class IteratorList<T> extends PreludeList<T> {
private Iterable<T> iterable;
private T headValue;
protected IteratorList(Iterable<T> iterable) {
this.iterable = iterable;
this.isEmpty = !iterable.iterator().hasNext();
if (!this.isEmpty) {
this.headValue = iterable.iterator().next();
}
} @Override
protected T getHead() {
if (!isEmpty) {
return headValue;
} throw new UnsupportedOperationException("Prelude Iterator empty");
} @Override
protected PreludeList<T> getTail() {
if (!isEmpty) {
return new IteratorList<T>(new Iterable<T>() {
@Override
public Iterator<T> iterator() {
Iterator<T> iterator = iterable.iterator();
iterator.next(); return iterator;
}
});
} return nilElem;
}
} private static class PreludeIterator<T> implements Iterator<T> {
private PreludeList<T> list; protected PreludeIterator(PreludeList<T> list) {
this.list = list;
} @Override
public boolean hasNext() {
return !PreludeList.nil(list);
} @Override
public T next() {
T result = list.getHead();
list = list.getTail();
return result;
}
} private T headItem;
private PreludeList<T> tailList;
protected boolean isEmpty = true; private static Nil nilElem = new Nil<>(); protected T getHead() {
return headItem;
} protected PreludeList<T> getTail() {
return tailList;
} private PreludeList() {} private PreludeList(T elem) {
this.headItem = elem;
this.tailList = nilElem;
this.isEmpty = false;
} private PreludeList(T elem, PreludeList<T> tailList) {
this.headItem = elem;
this.tailList = tailList;
this.isEmpty = false;
} public static <T> PreludeList<T> of(T ...elem) {
if (elem.length > 0) {
T _head = elem[0];
PreludeList<T> p = null;
for (int i = elem.length - 1; i > 0; --i) {
if (p != null) {
p = new PreludeList<T>(elem[i], p);
} else {
p = new PreludeList<T>(elem[i]);
}
} return new PreludeList<T>(_head, p);
} return nilElem;
} public static <T extends Number> PreludeList<T> range(T start, T stop, T step) {
return new RangeList<T>(start, stop, step, 0);
} public static <T> PreludeList<T> from(Iterable<T> iterable) {
if (iterable != null) {
return new IteratorList<T>(iterable);
} throw new UnsupportedOperationException("iterable is null");
} public static <T> Iterable<T> to(PreludeList<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new PreludeIterator<T>(list);
}
};
} public static <T> PreludeList<T> empty() {
return nilElem;
} public static <T> boolean nil(PreludeList<T> list) {
return list == null || list.isEmpty || list == nilElem;
} public static <T> PreludeList<T> cons(T elem, PreludeList<T> list) {
if (elem == nilElem) {
return list;
} if (list == nilElem) {
return new PreludeList<>(elem);
} return new PreludeList<>(elem, list);
} public static <T> PreludeList<T> cons(PreludeList<T> list, T elem) {
if (elem == nilElem) {
return list;
} if (list == nilElem) {
return new PreludeList<>(elem);
} return PreludeList.cons(list, new PreludeList<T>(elem));
} public static <T> PreludeList<T> cons(PreludeList<T> list1, PreludeList<T> list2) {
if (list1 == nilElem) {
return list2;
} if (list2 == nilElem) {
return list1;
} return new PreludeList<T>(list1.getHead(), cons(list1.getTail(), list2));
} public static <T> T head(PreludeList<T> list) {
if (!nil(list)) {
return list.getHead();
} throw new UnsupportedOperationException("Prelude list empty");
} public static <T> PreludeList<T> tail(PreludeList<T> list) {
if (!nil(list)) {
return list.getTail();
} throw new UnsupportedOperationException("Prelude list empty");
} public static <T> PreludeList<T> init(PreludeList<T> list) {
T t = head(list);
if (nil(list.getTail())) {
return nilElem;
} return new PreludeList<>(t, init(list.getTail()));
} public static <T> T last(PreludeList<T> list) {
T t = head(list);
if (nil(list.getTail())) {
return t;
} return last(list.getTail());
} public static <T> long length(PreludeList<T> list) {
if (nil(list)) {
return 0;
} return 1 + length(list.getTail());
} public static <T> T get(int pos, PreludeList<T> list) {
if (pos < 0) {
throw new IllegalArgumentException("pos is negative");
} if (nil(list)) {
throw new UnsupportedOperationException("prelude list is empty");
} if (pos == 0) {
return head(list);
} return get(pos - 1, tail(list));
} public static <T> PreludeList<T> repeat(T x) {
if (x == nilElem) {
throw new UnsupportedOperationException("The repeat operation doesn't support empty list");
} return new RepeatList<T>(x);
} public static <T> PreludeList<T> replicate(long count, T x) {
if (x == nilElem) {
throw new UnsupportedOperationException("The repeat operation doesn't support empty list");
} return take(count, repeat(x));
} public static <T> PreludeList<T> reverse(PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} return cons(reverse(list.getTail()), new PreludeList<T>(list.getHead()));
} public static <T> PreludeList<T> take(long count, PreludeList<T> list) {
if (count <= 0 || list.isEmpty) {
return nilElem;
} return new PreludeList<T>(list.getHead(), take(count -1, list.getTail()));
} public static <T> PreludeList<T> drop(long count, PreludeList<T> list) {
if (count <= 0 || list.isEmpty) {
return list;
} return drop(count - 1, list.getTail());
} public static <T> PreludeList<T> cycle(PreludeList<T> list) {
if (list == nilElem) {
throw new UnsupportedOperationException("The repeat operation doesn't support empty list");
} return new CycleList<T>(list);
} public static <T> PreludeList<T> iterate(Function<T, T> function, T x) {
return new IterateList<T>(function, x);
} public static <T, R> PreludeList<R> map(Function<T, R> function, PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} return new PreludeList<R>(function.apply(head(list)), map(function, list.getTail()));
} public static <T> PreludeList<T> filter(Predicate<T> predicate, PreludeList<T> list) {
if (nil(list)) {
return list;
} if (!predicate.test(head(list))) {
return filter(predicate, list.getTail());
} else {
return new PreludeList<>(head(list), filter(predicate, list.getTail()));
}
} public static <T, R> PreludeList<R> flatMap(Function<T, PreludeList<R>> function, PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} return PreludeList.cons(function.apply(head(list)), flatMap(function, list.getTail()));
} public static <T> PreludeList<PreludeList<T>> splitAt(int count, PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} return new PreludeList<PreludeList<T>>(take(count, list), splitAt(count, drop(count, list)));
} public static <T> PreludeList<PreludeList<T>> splitAt(Predicate<T> predicate, PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} PreludeList<T> elem = PreludeList.nilElem;
PreludeList<T> loopList = list;
while (!nil(loopList)) {
T headItem = head(loopList);
elem = PreludeList.cons(elem, new PreludeList<T>(headItem));
if (!predicate.test(headItem)) {
loopList = tail(loopList);
} else {
break;
}
} return !nil(loopList) ? PreludeList.cons(elem, splitAt(predicate, tail(loopList))) : new PreludeList<PreludeList<T>>(elem);
} private static <T> int elemIndex(T x, PreludeList<T> list, int pos) {
if (nil(list)) {
return -1;
} T t = head(list);
if (t.equals(x) || t == x) {
return pos;
} return elemIndex(x, tail(list), pos + 1);
} public static <T> int elemIndex(T x, PreludeList<T> list) {
return elemIndex(x, tail(list), 0);
} private static <T> PreludeList<Integer> elemIndices(T x, PreludeList<T> list, int pos) {
if (nil(list)) {
return nilElem;
} T t = head(list); return t.equals(x) || t == x ? PreludeList.cons(pos, elemIndices(x, tail(list), pos + 1)) : elemIndices(x, tail(list), pos + 1);
} public static <T> PreludeList<Integer> elemIndices(T x, PreludeList<T> list) {
return elemIndices(x, tail(list), 0);
} private static <T> T find(Predicate<T> predicate, PreludeList<T> list) {
if (nil(list)) {
throw new IllegalArgumentException("Can't find value");
} T t = head(list);
if (predicate.test(t)) {
return t;
} return find(predicate, tail(list));
} private static <T> int findIndex(Predicate<T> predicate, PreludeList<T> list, int pos) {
if (nil(list)) {
return -1;
} T t = head(list);
if (predicate.test(t)) {
return pos;
} return findIndex(predicate, tail(list), pos + 1);
} public static <T> int findIndex(Predicate<T> predicate, PreludeList<T> list) {
return findIndex(predicate, tail(list), 0);
} private static <T> PreludeList<Integer> findIndices(Predicate<T> predicate, PreludeList<T> list, int pos) {
if (nil(list)) {
return nilElem;
} T t = head(list); return predicate.test(t) ? PreludeList.cons(pos, findIndices(predicate, tail(list), pos + 1)) : findIndices(predicate, tail(list), pos + 1);
} public static <T> PreludeList<Integer> findIndices(Predicate<T> predicate, PreludeList<T> list) {
return findIndices(predicate, tail(list), 0);
} //partition even [2,4,6,7,9,10,11] ==> ([2,4,6,10],[7,9,11])
public static <T> PreludeList<PreludeList<T>> partition(Predicate<T> predicate, PreludeList<T> list) {
if (nil(list)) {
return nilElem;
} return PreludeList.cons(new PreludeList<PreludeList<T>>(filter(predicate, list)), new PreludeList<PreludeList<T>>(filter(predicate.negate(), list)));
} @Override
public String toString() {
if (isEmpty) {
return "[]";
} StringBuilder stringBuilder = new StringBuilder("[");
PreludeList<T> list = this;
while (!list.isEmpty) {
T t = list.getHead(); stringBuilder.append(t.toString()); try {
list = list.getTail();
if (!list.isEmpty) {
stringBuilder.append(",");
}
} catch (UnsupportedOperationException e) {
break;
}
} stringBuilder.append("]"); return stringBuilder.toString();
}
}

使用Java实现haskell-style的list的更多相关文章

  1. java之google style

    Google的Java编码规范英文版: http://google-styleguide.googlecode.com/svn/trunk/javaguide.html Google的Java编码规范 ...

  2. JAVA开发CHECK STYLE

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE module PUBLIC "-/ ...

  3. java 去掉html/style/css等标签

    //定义script的正则表达式 private static String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/sc ...

  4. 在IntelliJ IDEA中配置Google Java Code Style及代码格式化快捷键

    google-java-format plugin should intercept the “Reformat Code” action in IDEA (Ctrl+Alt+L) and apply ...

  5. [JAVA] 一个可以编辑、编译、运行Java简单文件的记事本java实现

    本来是Java课做一个仿windows记事本的实验,后来突然脑子一热,结果就给它加了一个编译运行Java文件的功能. 本工程总共大约3000行代码,基本上把所学的java界面.文件.控件的功能都包含在 ...

  6. Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)

    MD5和RSA是网络传输中最常用的两个算法,了解这两个算法原理后就能大致知道加密是怎么一回事了.但这两种算法使用环境有差异,刚好互补. 一.MD5算法 首先MD5是不可逆的,只能加密而不能解密.比如明 ...

  7. 【总结】java命令解析以及编译器,虚拟机如何定位类

    学Java有些日子了,一直都使用IDE来写程序.这样的好处就是能让我连如何用命令行编译,解释执行Java源代码都不知道,就更不清楚JDK中的编译器和虚拟机(包含字节码解释器)是如何定位到类文件的.悲哀 ...

  8. Java开发常用代码

    1. 字符串有整型的相互转换 String a = String.valueOf(2); //integer to numeric string int i = Integer.parseInt(a) ...

  9. java.util.logging.Logger基础教程

    从JDK1.4开始即引入与日志相关的类java.util.logging.Logger,但由于Log4J的存在,一直未能广泛使用.综合网上各类说法,大致认为: (1)Logger:适用于小型系统,当日 ...

  10. JAVA设计模式(09):结构化-代理模式(Proxy)

    一,定义:  代理模式(Proxy):为其它对象提供一种代理以控制对这个对象的訪问. 二.其类图: 三,分类一:静态代理 1,介绍:也就是须要我们为目标对象编写一个代理对象,在编译期就生成了这个代理对 ...

随机推荐

  1. 清北学堂 2020 国庆J2考前综合强化 Day7

    目录 1. 题目 T1 魔力石 题目描述 Sol T2 和 题目描述 Sol T3 数对 题目描述 Sol T4 海豹王国 题目描述 Sol 考场策略 1. 题目 T1 魔力石 题目描述 题目描述 小 ...

  2. 使用.NET简单实现一个Redis的高性能克隆版(七-完结)

    译者注 该原文是Ayende Rahien大佬业余自己在使用C# 和 .NET构建一个简单.高性能兼容Redis协议的数据库的经历. 首先这个"Redis"是非常简单的实现,但是他 ...

  3. ACM模式细节

    牛客网的ACM模式需要自己写输入输出,在这里简单记录一下: 基本答题框架: import java.util.*; public class Main{ public static void main ...

  4. Dynamic CRM一对多关系的数据删除时设置自动删除关联的数据

    在业务实体中主子表非常常见,然后子表可能有会有自己的子表或者多对多关系,在删除的业务场景下,删除主数据,剩余的子数据就成了脏数据, 之前的做法是,监听主表的删除事件,然后在插件中找到其下的子表数据然后 ...

  5. dentry的引用计数不对导致的crash

    [17528853.189372] python invoked oom-killer: gfp_mask=0xd0, order=0, oom_score_adj=-998[17528853.189 ...

  6. 对DDD使用的一些建议

    群里经常看到类似于"看了DDD之后就不会写代码了"的情况,趁最近学车的间隙,写写我的看法. 关于这个事儿,我是觉得:当没有DDD的时候,如果你知道怎么做,那就那么做好了,不要考虑D ...

  7. [NOIP2018提高组] 保卫王国 (树链剖分+动态DP)

    题面 题目链接-Luogu 题目链接-Loj(要加Freopen) 题解 什么是动态DP? OneInDark:你不需要知道这么多,你只需要知道是利用了广义矩阵乘法就够了! 广义矩乘 广义矩阵乘法,简 ...

  8. LOJ#2014「SCOI2016」萌萌哒(倍增,并查集优化连边)

    题面 点此看题 题意很明白,就不转述了吧. 题解 题目相当于告诉了我们若干等量关系,每个限制 l 1 , r 1 , l 2 , r 2 \tt l_1,r_1,l_2,r_2 l1​,r1​,l2​ ...

  9. 【MySQL】从入门到掌握2-下载安装

    上期:[MySQL]从入门到掌握1-一些背景知识 第一章:下载 官网下载地址: https://dev.mysql.com/downloads/mysql/ https://dev.mysql.com ...

  10. 【java】学习路径25-ArrayList类,Vector类,LinkedList类的使用和区别,Iterator迭代器的使用

    ArrayList的使用 ArrayList类:可变化长度的数组. 与一般的数组不同的是,其长度不固定,可以添加任意类型的数据. 也可以添加不同类型的数据,但是一般不这么做. ArrayList类位于 ...