Haskell-功能不使用无限列表

发布于 2025-01-27 19:31:19 字数 511 浏览 2 评论 0原文

我写了一个功能,将清单以各种可能的方式将列表切成一半。 我的问题是我使用了“ lenght”功能,因此无法与无限列表一起使用。 我想不出任何实际修复的东西。 知道我该如何解决这个问题?

示例:

splitList "home"= [("","home"),("h","ome"),("ho","me"),("hom","e"),("home","")]

我的代码:

splitList :: [a] -> [([a],[a])]
splitList a = splitList' a

splitList' ::  [a] -> [([a],[a])]
splitList' a =  take ((length a)+1)  (splitList'' 0 a)

splitList'' :: Int -> [a] -> [([a],[a])]
splitList'' i a = (splitAt i a) : splitList'' (i+1) a 

I wrote a function which cuts a list into half in every possible way.
My problem is that I used the 'lenght' function so it can't work with infinite lists.
I couldn't think of anything that actually fixed this.
Any idea how could I solve this problem?

Example:

splitList "home"= [("","home"),("h","ome"),("ho","me"),("hom","e"),("home","")]

My code:

splitList :: [a] -> [([a],[a])]
splitList a = splitList' a

splitList' ::  [a] -> [([a],[a])]
splitList' a =  take ((length a)+1)  (splitList'' 0 a)

splitList'' :: Int -> [a] -> [([a],[a])]
splitList'' i a = (splitAt i a) : splitList'' (i+1) a 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2025-02-03 19:31:19

长度a将被困在无限列表上的无限循环中。因此,您将需要以另一种方式进行重复。您可以在列表上重复出现,直到到达列表的末尾,例如:

splitList :: [a] -> [([a],[a])]
splitList [] = [([], [])]
splitList xa@(x:xs) = ([], xa) : map … (splitList xs)

在这里您需要填写零件,splitlist xs xs您用x将每个2键盘的第一项准备。

length a will get stuck in an infinite loop on an infinite list. You thus will need to recurse in another way. You can recurse on the list until you reach the end of the list, for example with:

splitList :: [a] -> [([a],[a])]
splitList [] = [([], [])]
splitList xa@(x:xs) = ([], xa) : map … (splitList xs)

here you need to fill in the part where for each tuple in splitList xs you prepend the first item of each 2-tuple with x.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文