简体   繁体   中英

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? 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 part is a pattern match guard condition.

It seems there would be a simpler way of doing this using functions from Data.List

:m + Data.List
let mkList to count = (concat . replicate count) [1..to]
mkList 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]
mkList 1 10
[1,1,1,1,1,1,1,1,1,1]

Instead of replicate you could also use take and cycle

let mkList to count = take count $ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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