![](/img/trans.png)
[英]How to return the first n-1 elements of a list of length n in Haskell?
[英]Haskell: A function that takes a list xs and an integer n and returns all list of length n with elements from xs
我之前曾尝试解决此问题,但是我一直在寻找解决方案,但从未找到解决方案。
我需要一个函数,该函数需要一个列表xs和一个整数n,并返回所有长度为n的列表,其中包含来自xs的元素。 例如:
function [0,1] 3 = [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
我已经试过了:
list _ 0 = []
list xs n = do
y <- xs
ps <- list xs (n-1)
return y : ps
和这个:
list _ 0 = []
list xs n = do
y <- xs
y : list xs (n-1)
没有按预期方式工作。 我想知道两件事:为什么这些都不起作用? 我应该如何修改它们以使其起作用?
你很亲密! 您的问题是您的基本情况, list _ 0 = []
。
您要说的是,没有长度为0且带有xs元素的列表,而实际上只有一个空列表。
尝试
list _ 0 = [[]]
list xs n = do
y <- xs
ps <- list xs (n-1)
return $ y : ps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.