[英]Haskell Recursion Scanl
I am trying to recursively pass in different values looping over eachother to be put into a function. 我试图递归地传递遍历彼此的不同值以放入函数中。 I have this so far: 到目前为止,我有:
randNum f = take 20 (iterate f 300)
where f n = scanl (mod') (n*2 + 75) getInts
( getInts
is simply cycle
and a list of numbers) ( getInts
只是cycle
和数字列表)
The randNum
function is then used in the following way: 然后按以下方式使用randNum
函数:
randGenPoints :: [Point]
randGenPoints = pairs (randNum 1)
However I have a problem where in the randNum
I get this error: 但是我有一个问题,在randNum
我得到这个错误:
*** Expression : iterate f 300
*** Term : f
*** Type : Integer -> [Integer]
*** Does not match : [Integer] -> [Integer]
All I want is to have a continuously modifying list for the mod value in my function and i'm stuck and can't quite get it working.... 我只想在我的函数中有一个不断修改的mod值列表,而我陷入了困境,无法完全正常工作...。
Any advice would be much appreciated :), 任何建议将不胜感激:),
Thanks 谢谢
You are passing f
, and at the same time you're redefining f
. 您正在传递f
,同时又在重新定义f
。 While this is perhaps not the real error, it is quite confusing. 尽管这可能不是真正的错误,但令人困惑。 Think about it and correct, please. 考虑一下,请纠正。
iterate
has type iterate
有类型
iterate :: (a -> a) -> a -> [a]
It takes a function of type a -> a
, which in your case is specialized to Integer -> Integer
. 它具有a- a -> a
类型的函数,在您的情况下,该函数专门用于Integer -> Integer
。 However, the f
you define in the where clause is of type Integer -> [Integer]
. 但是,您在where子句中定义的f
类型为Integer -> [Integer]
。 That happens because scanl
, rather than just reducing a list to a value with some binary function, gives back a list with all intermediate values: 发生这种情况是因为scanl
而不是仅仅使用某些二进制函数将列表缩减为一个值,而是返回了一个包含所有中间值的列表:
*Main> :t scanl
scanl :: (a -> b -> a) -> a -> [b] -> [a]
*Main> scanl (+) 0 [1..5]
[0,1,3,6,10,15]
As far as the type errors go, you probably want a fold, such as foldl'
from Data.List
. 就类型错误而言,您可能想要折叠,例如Data.List
foldl'
。
*Main> :t foldl'
foldl' :: (a -> b -> a) -> a -> [b] -> a
*Main> foldl' (+) 0 [1..5]
15
That, however, will not solve all of your problems. 但是,那并不能解决您的所有问题。 For one, if getInts
is an infinite list as you imply, then a fold on it will not terminate. 例如,如果getInts
是您所暗示的无限列表,则对其的折叠不会终止。
PS: Note that, as Ingo pointed out, the f
argument to randNum
is not the same f
defined in the where clause; PS:请注意,正如Ingo所指出的, randNum
的f
参数与where子句中定义的f
; it is superfluous. 这是多余的。
For random numbers, you're using something like 对于随机数,您正在使用类似
nextPseudoRandom n = n^2 +75 `mod` 234
right? 对? You could maybe achieve what you want by doing 你也许可以通过做来达到你想要的
randNum = iterate (map nextPseudoRandom) (getInts)
so pointwise generated noise. 因此逐点产生噪音。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.