0

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

这就是我目前所处的位置。

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

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

Couldn't match type ‘Char’ with ‘[t]’
Expected type: [[t]]
  Actual type: [Char]
Relevant bindings include
  it :: [t] -> [[t]] (bound at <interactive>:18:1)
In the first argument of ‘prefixess’, namely ‘"abcde"’
In the expression: prefixess "abcde"
In an equation for ‘it’: it = prefixess "abcde"

我没主意了。有什么提示吗?

4

2 回答 2

2

我不认为这段代码做你认为它做的事情。您尝试将列表 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' [] = [[]]

此函数在 Data.List 中的名称“inits”下也可用

Main> import Data.List
Main Data.List> inits "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]
于 2017-01-22T14:10:59.817 回答
0

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

prefixes = foldr (\el acc -> [] : map (el:) acc) [[]] 
于 2020-02-10T18:10:11.780 回答