简体   繁体   English

Haskell:Let语句在函数声明中使用先前声明的变量

[英]Haskell: Let statement using previous declared variable in function declaration

Say I have the function 说我有功能

foo n = foo' 1 where
    foo' n = foo' 1
    foo' x = x : foo' (x + 1)

As an example, say n = 5 is it possible to make the meaning of foo' n be foo' 5? 例如,假设n = 5是否可以使foo'n的含义为foo'5? So it will loop over. 因此它将循环。

I guess what you're asking for is this: 我猜您要的是这样的:

foo n = foo' 1 
  where
    foo' x | x == n = foo' 1
    foo' x = x : foo' (x + 1)

The | x == n | x == n | x == n part is a pattern match guard condition. | x == n part是模式匹配保护条件。

It seems there would be a simpler way of doing this using functions from Data.List 似乎有一种使用Data.List中的函数来完成此操作的简单方法

:m + Data.List :m + Data.List
let mkList to count = (concat . replicate count) [1..to] 让mkList计数=(连续。复制计数)[1..to]
mkList 5 9 清单5 9
[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5 ,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
mkList 1 10 mkList 1 10
[1,1,1,1,1,1,1,1,1,1] [1,1,1,1,1,1,1,1,1,1,1]

Instead of replicate you could also use take and cycle 除了复制之外,您还可以使用takecycle

let mkList to count = take count $ cycle [1..to] 让mkList进行计数=进行计数$ cycle [1..to]

take and cycle would be cheaper since you wouldn't have to go back and concat the lists. 乘车和骑自行车会更便宜,因为您不必回头去整理清单。

Or you could also use iterate 或者你也可以使用迭代

((take 10 $ iterate (+1) 0) == [0..9]) == True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM