Haskell中的所有列表循环 [英] All list rotations in Haskell

查看:181
本文介绍了Haskell中的所有列表循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来旋转列表:

  rotate :: [a]  - > [a] 
rotate [] = []
rotate(x:xs)= xs ++ [x]

现在我想要一个函数给出一个列表,列出每个可能的有限列表旋转:

  rotateAll :: [a]  - >在命令式语言中,我会做类似于(以伪代码的形式)的内容。[/ b] [b] [b] [b] [b]对于i = 1到列表的长度
追加列表到rotateList
list = rotate(list)

$ b

  $ b  

当然,必要的思考可能不会帮助我找到解决此问题的功能性解决方案。我正在寻找一些关于如何解决这个问题的提示。



其他想法

为了解决这个问题,我有两个问题需要解决。首先,我需要重复旋转一个列表并将每个结果收集到一个列表中。因此,第一个解决方案需要做一些类似于

  rotateAll xs = [xs(rotate xs)(rotate(rotate xs))(旋转(旋转(旋转xs)))...] 

当然,我不知道如何很多时候这样做。我会满意地做到这一点,然后使用 take(length xs)来获得我想要的有限数量的列表。这实际上证明了第二个问题:确定何时停止。我不知道使用是解决问题的最有效或最优雅的方法,但是当我输入这个内容时它就浮现出来了,应该可以工作。



附录:
现在我已经找到了两种解决方案,我很乐意欢迎任何其他更快或使用不同方法的解决方案。谢谢!

解决方案

迭代,你可以编写一个函数来生成n个循环的列表。情况n = 0会将输入包装在一个列表中,并且情况n = m + 1会将输入附加到情况m的结果中。虽然使用标准功能通常是首选,但有时编写自己的解决方案是健康的。

I have a function to rotate a list:

rotate :: [a] -> [a]
rotate [] = []
rotate (x:xs) = xs ++ [x]

Now I want a function that gives a list with every possible rotation of a finite list:

rotateAll :: [a] -> [[a]]

In a imperative language, I would do something like (in pseudocode)

for i = 1 to length of list
  append list to rotateList
  list = rotate(list)

Of course, thinking imperatively probably doesn't help me find a functional solution to this problem. I'm looking for some hints as to how to tackle this.

Additional thoughts:

To solve this, I have two issues to tackle. First I need to repeatedly rotate a list and collect each result into a list. So a first solution needs to do something like

rotateAll xs = [xs (rotate xs) (rotate (rotate xs)) (rotate (rotate (rotate xs))) ...]

Of course I don't know how many times to do this. I'd be satisfied to do this infinitely and then use take (length xs) to get the finite number of lists I desire. This actually demonstrates the second issue: determining when to stop. I don't know if using take is the most efficient or elegant way to solve the problem, but it came to mind as I was typing this and should work.

Addendum: Now that I have found two solutions on my own or with hints. I will gladly welcome any other solutions that are faster or use different approaches. Thanks!

解决方案

Aside from iterate, you could write a function that generates a list of n rotations. Case n=0 would just wrap the input in a list and case n=m+1 would append the input to the result of case m. Although using standard functions is generally preferred, sometimes writing your own solutions is healthy.

这篇关于Haskell中的所有列表循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆