I wrote a simple Haskell function, that gives a list of primes.
primes' :: [Int] -> [Int]
primes' (p : xs) = p : primes' (filter (x -> x `rem` p /= 0) xs)
primes :: [Int]
primes = primes' [2 ..]
On each step it gives a filter of numbers not divisible by first element.
As far as I understand, p
is saved as a part of filter condition, and it saved on a stack by calling primes'
recursively.
I want to implement the same behavior in C.
I know that filter is a generator coroutine, and that such behavior can be implemented using either state variables, or setjmp.h
, but I can figure out how to do this.
Note that I don’t want any arrays, in particular, I don’t want to call malloc/realloc
, and I understand that it might be a simpler approach in terms of C. I want to do this using stack memory, just as Haskell program does (although I understand that Haskell probably allocates memory for lists, to create a generator).
If there is a way to avoid setjmp
by passing additional state argument it is probably better, but setjmp
is fine.
Also, if there is any kind of mathematical analysis on these computations, it will be even better.
As I writing this, I start to think there is no way to avoid dynamic allocation, but I don’t know how to prove it.