Functional programming 在SML中使溪流变平
我有以下数据类型:Functional programming 在SML中使溪流变平,functional-programming,sml,smlnj,Functional Programming,Sml,Smlnj,我有以下数据类型: datatype 'a stream' = Susp of unit -> 'a stream and 'a stream = Empty | Cons of 'a * 'a stream' 我想写一个展平函数,它的类型如下 flatten: ’a stream’ stream’ -> ’a stream’ 展平函数将流作为输入,并通过附加流来展平 我该怎么做?有什么想法吗 谢谢 编辑:我知道如何对列表进行编辑。这很简单: fun flatten[]=[]|
datatype 'a stream' = Susp of unit -> 'a stream
and 'a stream = Empty | Cons of 'a * 'a stream'
我想写一个展平函数,它的类型如下
flatten: ’a stream’ stream’ -> ’a stream’
展平函数将流作为输入,并通过附加流来展平
我该怎么做?有什么想法吗
谢谢
编辑:我知道如何对列表进行编辑。这很简单:
fun flatten[]=[]| flat(l::ls)=l@flatten ls代码>
请帮助我处理流,我不知道如何匹配流中的流。让我们先为列表编写:
fun append(xs, ys) = case xs of
[] => ys
| (x::xs) => x :: append(xs, ys)
fun flatten(xss) = case xss of
[] => []
| (xs::xss) => append(xs, flatten(xss))
上述情况应该是显而易见的。现在,我们只需稍微更改它以支持stream
,方法是Susp
在适当的步骤结束并force
-ing:
fun force(Susp(xs)) = xs()
fun append(xs, ys) = case force xs of
Empty => ys
| Cons(x,xs) => Susp(fn () => Cons(x, append(xs, ys)))
fun flatten(xss) = case force xss of
Empty => Susp(fn () => Empty)
| Cons(xs,xss) => append(xs, flatten(xss))
让我们先为列表编写它:
fun append(xs, ys) = case xs of
[] => ys
| (x::xs) => x :: append(xs, ys)
fun flatten(xss) = case xss of
[] => []
| (xs::xss) => append(xs, flatten(xss))
上述情况应该是显而易见的。现在,我们只需稍微更改它以支持stream
,方法是Susp
在适当的步骤结束并force
-ing:
fun force(Susp(xs)) = xs()
fun append(xs, ys) = case force xs of
Empty => ys
| Cons(x,xs) => Susp(fn () => Cons(x, append(xs, ys)))
fun flatten(xss) = case force xss of
Empty => Susp(fn () => Empty)
| Cons(xs,xss) => append(xs, flatten(xss))
我想这是家庭作业。我建议你先尝试将列表展平,然后使其适应流。@AndreasRossberg,我知道如何处理列表。很简单:fun flatten[]=[]| flat(l::ls)=l@flatten ls代码>请帮助我处理流,我不知道如何对流中的流进行模式匹配。您可以像往常一样进行模式匹配:fun flatte Empty=…|展平(Cons(x,xs))=…
。您还需要在流上定义append
。剩下的唯一诀窍就是在正确的位置插入fn
。我想这是家庭作业。我建议你先尝试将列表展平,然后使其适应流。@AndreasRossberg,我知道如何处理列表。很简单:fun flatten[]=[]| flat(l::ls)=l@flatten ls代码>请帮助我处理流,我不知道如何对流中的流进行模式匹配。您可以像往常一样进行模式匹配:fun flatte Empty=…|展平(Cons(x,xs))=…
。您还需要在流上定义append
。剩下的唯一技巧是在正确的位置插入fn
。