使用Haskell生成1到10的简单列表

发布于 2025-01-31 07:00:55 字数 463 浏览 2 评论 0原文

我是哈斯克尔(Haskell)的新来者,可以帮助我如何生成1到10的清单。

我试图这样做:

seqList :: Integer -> [Integer]
seqList 1 = [1]
seqList n = n : seqList(n-1)

结果10到1,而不是1到10

和第二个问题 我们可以使函数作为价值吗?

numList :: [Integer]
numList =  [1,2..10]
totJum :: Int
totJum = length numList

takeNum :: Int->[Integer]
takeNum totJum
  | totJum >= 10 = take 5 numList
  | totJum == 10  = numList

使用此代码,如果数字的长度与条件匹配,我想调用输出。

I am new in Haskell, could guys help me how to generating list from 1 to 10.

I tried to make like this:

seqList :: Integer -> [Integer]
seqList 1 = [1]
seqList n = n : seqList(n-1)

The result 10 to 1, not 1 to 10

And second question
can we make function as value.

numList :: [Integer]
numList =  [1,2..10]
totJum :: Int
totJum = length numList

takeNum :: Int->[Integer]
takeNum totJum
  | totJum >= 10 = take 5 numList
  | totJum == 10  = numList

With this code, i want to call output if the length from numlist matches the condition.

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

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

发布评论

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

评论(1

怪我太投入 2025-02-07 07:00:55

对于第一个,您可以使用累加器:用于产生值的变量,并在递归调用中每次增加,因此:

seqList :: Integer -> [Integer]
seqList n = go 1
    where go i
              | i <= … = …
              | otherwise = …

我在…零件作为锻炼。

使用此代码,如果来自数字的长度与条件匹配,我想调用输出。

您不应将totjum用作参数,而应仅在功能正文中使用它,因此

takeNum :: [Integer]
takeNum
  | totJum >= 10 = take 5 numList
  | totJum == 10  = numList

请注意,您不涵盖totjum更少的情况比或10。在这种情况下,函数因此会误差。因此,您可能需要添加否则子句。

For the first one you can work with an accumulator: a variable you use to yield a value and each time increment in the recursive call, so:

seqList :: Integer -> [Integer]
seqList n = go 1
    where go i
              | i <= … = …
              | otherwise = …

where I leave filling in the parts as an exercise.

with this code, I want to call output if the length from numlist matches the condition.

You should not use totJum as a parameter, but just use it in the body of the function, so:

takeNum :: [Integer]
takeNum
  | totJum >= 10 = take 5 numList
  | totJum == 10  = numList

Note however that here you do not cover the case where totJum is less than or 10. In that case the function will thus error. You thus might want to add an otherwise clause.

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