haskell中的前缀列表

时间:2017-01-22 13:29:55

标签: string haskell prefixes

我要写一个函数,它返回给定字符串的所有前缀的列表。

这是我到目前为止的地方。

Where PostalCode = And AddressLine1  = and AddressLine2 = 

它编译,但是当我尝试在字符串上运行时,我得到了这个:

prefixess [x] [] = [x]
prefixess [] s = prefixess [s] s
prefixess [x] s  = prefixess [x, (init s)] (init s)
prefixes s = prefixess [] s

我没有想法。任何提示?

2 个答案:

答案 0 :(得分:1)

我不认为这段代码符合您的想法。您尝试将列表x与模式[x]进行模式匹配,模式[x]捕获单个列表的元素。如果我像这样修复你的代码,它可以工作:

prefixess x [] = x
prefixess [] s = prefixess [s] s
prefixess x s  = prefixess ((init s):x) (init s)
prefixes s = prefixess [] s

这给出了以下结果:

Main> prefixes "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]

但是你真的不需要一个计算前缀的函数的累加器,我会这样写:

prefixes' (x:xs) = [] : (map (x:) (prefixes xs))
prefixes' [] = [[]]

此功能也可以名称" inits"在Data.List

Main> import Data.List
Main Data.List> inits "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]

答案 1 :(得分:0)

用于生成所有前缀列表的无点样式解决方案:

prefixes = foldr (\el acc -> [] : map (el:) acc) [[]]