Haskell 交织函数

Haskell 交织函数,haskell,recursion,Haskell,Recursion,我发现这段代码构建了一个列表,对应于: 这是完美的,创造了奇迹,但我不能把我的头围绕着它。例如: > take 8 thueMorse [0,1,1,0,1,0,0,1] 如果全局定义交错函数并使用它,我会得到一个异常,这是正确的: > let interleave (x:xs) ys = x : interleave ys xs > interleave [1,2,3] [4,5,6] [1,4,2,5,3,6*** Exception: <interactive&

我发现这段代码构建了一个列表,对应于:

这是完美的,创造了奇迹,但我不能把我的头围绕着它。例如:

> take 8 thueMorse 
[0,1,1,0,1,0,0,1]
如果全局定义
交错
函数并使用它,我会得到一个异常,这是正确的:

> let interleave (x:xs) ys = x : interleave ys xs
> interleave [1,2,3] [4,5,6]
[1,4,2,5,3,6*** Exception: <interactive>:29:5-47: Non-exhaustive patterns in function interleave
>让交织(x:xs)ys=x:interleave ys-xs
>交织[1,2,3][4,5,6]
[1,4,2,5,3,6***异常::29:5-47:函数交织中的非穷举模式

那么,上面的工作原理是什么?是因为它是一个无限的列表,所以可以安全地永远交叉吗?

异常已经告诉您错误:
交叉
的模式并不详尽。如果您尝试使用
交叉[]a
?第一个参数的模式仅与至少有一个元素的列表匹配。这样,不是所有可能的列表都匹配。

是的,它工作,因为输入是一对无限列表。
交错的定义只处理第一个参数不为空的情况,即使用
构造函数。但是列表有第二个构造函数(
[]
),该定义可能会忽略该构造函数。更完整的定义可能是这样的,具体取决于您希望它如何处理空输入:

interleave (x:xs) ys = x : interleave ys xs
interleave [] ys = ys
interleave (x:xs) ys = x : interleave ys xs
interleave [] ys = ys