递归地反转字符串(或列表)
我正在尝试在 haskell 中编写一个函数来递归地反转列表。我编写了一个辅助函数,它采用原始列表和一个空列表,然后以 LIFO 模式将元素从第一个列表传输到另一个列表。
这就是我所拥有的:
myreverse :: [a] -> [a]
myreverse list = myflip list []
myflip :: [a] -> [a] -> [a]
myflip list1 newList
| null list1 = newList
| otherwise = myflip (tail list1) ((head list1) : newList)
我知道有一个内置函数可以为我完成此操作,但要求是我只使用 head、tail、elem 和 null (也没有模式匹配)。所以我的问题是:是否有更好的解决方案,我只有一个函数 myreverse,仅消耗一个列表? (当然满足上述要求)
谢谢!
I'm trying to write a function in haskell that reverses lists recursively. I wrote a helper function that takes the original list and an empty list then transfers elements from the first one to the other in a LIFO pattern.
Here's what I have:
myreverse :: [a] -> [a]
myreverse list = myflip list []
myflip :: [a] -> [a] -> [a]
myflip list1 newList
| null list1 = newList
| otherwise = myflip (tail list1) ((head list1) : newList)
I know there's a built-in function that does it for me but the requirement is that I only use head, tail, elem and null (No pattern matching either). So my question is: is there a better solution where I only have one function, myreverse, that consumes only one list? (That meets the requirements above, of course)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试使用
foldl
反转列表,如下所示:You can try reversing a list using
foldl
like so:因此,对于任何可能感兴趣的人,这就是我最终写的内容:
感谢大家的评论和建议。
So for anyone who might be interested, this is what I ended up writing:
Thanks everyone for your comments and suggestions.
将其保存在reverse.hs文件中
然后运行
反向字符串“abc”
save this in reverse.hs file
then run
reverseString "abc"
除了满足您的额外要求所需的调整之外,您的功能相当于
reverse
在 GHC 中实现。因此我认为你的功能是相当不错的。Aside from the adjustments necessary to meet your additional requirements, your function is equivalent to the way
reverse
is implemented in GHC. Therefore I'd assume your function is pretty good the way it is.这个功能满足您的要求,但效率非常低:
您的解决方案一点也不差。使用模式匹配并使
myFlip
成为本地函数后,它看起来不会难看。将局部函数与累加器一起使用的技术非常常见(尽管不是在如此简单的情况下)。This function fulfills your requirements, but is horrible inefficient:
Your solution isn't bad at all. After using pattern matching and making
myFlip
a local function it wouldn't look ugly. And the technique of using a local function with an accumulator is very common (although not in such easy cases).