【发布时间】:2019-08-08 00:42:43
【问题描述】:
我正在尝试编写一个函数,该函数将元组中的数据转换为执行运行长度编码的程序的字符串。我之前使用 append 编写过它,但我一直在尝试改进它。
函数 decode 应该接受一个元组列表,然后返回一个字符串。
示例
> decode [('h',7),('s',3),('g',1)]
"hhhhhhhsssg"
> decode [('z',9),('z',1)]
"zzzzzzzzzz"
我最初使用 append 函数递归地编写它,它工作正常但不是最佳的,我当前的实现看起来是这样的:
decode :: [(Char,Int)] -> String
decode [] = []
decode x = concat(replicate (snd (head x)) (fst (head x)) : decode (tail x)
这会给我一个编译错误,因为decode (tail x) 部分不符合我不允许更改的类型声明。我确信这是不好的做法,但有没有办法让程序在完成递归之前不符合类型声明?
* Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
Actual type: String
* In the second argument of `(:)', namely `decode (tail x)'
In the first argument of `concat', namely
`(replicate (snd (head x)) (fst (head x)) : decode (tail x))'
In the expression:
concat (replicate (snd (head x)) (fst (head x)) : decode (tail x))
|
35 | decode x = concat(replicate (snd (head x)) (fst (head x)) : decode (tail x))
|
【问题讨论】:
-
这有什么问题?
let x = [('h',7),('s',3),('g',1)] in concat [replicate n c | (c, n) <- x]. -
为什么要折叠?
(snd (head x))是什么东西?decode ((c, n) : xs) = replicate n c ++ decode xs对我来说似乎更简单。 -
是的:几乎总是,模式匹配比
fst/snd等更可取,特别是head和tail是evil。 -
如果你真的想要深奥,那么
decode = concatMap (uncurry (flip replicate))。 -
@Ali
(++)的问题发生在您重复将短字符串附加到较长字符串时。在这里,您正在做相反的事情:在短字符串的末尾添加一个长字符串。
标签: haskell recursion types tuples