The standard way to execute code in Haskell

In the following generic code:

nat = [1..xmax] xmax = *insert arbitrary Integral value here* setA = [2*x | x <- nat] setB = [3*x | x <- nat] setC = [4*x | x <- nat] setD = [5*x | x <- nat] setOne = setA `f` setB setTwo = setC `f` setD setAll = setOne ++ setTwo setAllSorted = quicksort setAll 

(note that 'f' means a function like

 f :: Integral a => [a] -> [a] -> [a] 

not just ++)

How does Haskell handle the attempt to print setAllSorted?

Does it get the values ​​for setA and setB, compute setOne, and then store the values ​​for setOne in memory (before calculating everything else)?

Or does Haskell store everything in memory until it gets the value for setAllSorted?

If so, then how would I indicate (using main, do functions and all those other IO objects) what does it do instead?

Can I tell the program in what order to collect and collect garbage? If so, how do I do this?

+6
source share
2 answers

The setAllSorted head setAllSorted necessarily less than or equal to each element in the tail. Therefore, to determine the head, it is necessary to calculate all setOne and setTwo . In addition, since all sets are permanent applicative forms, I believe that they will not collect garbage after calculation. The numbers themselves will most likely be split between the sets, but the cons nodes that stick them together will most likely not (your luck with some will depend on the definition of f ).

+9
source

Because of laziness, Haskell evaluates things on demand. You can think of the print done at the end as “pulling” items from the setAllSorted list, and this may entail other things.

That is, by running this code, it looks something like this:

  • Print first evaluates the first setAllSorted element.
  • Since this comes from the sorting procedure, this will require all setAll elements. (Since the smallest element may be the last).
  • Evaluating the first setAll element requires evaluating the first setOne element.
  • The evaluation of the first setOne element depends on how f is implemented. This may require an assessment of all or none of setA and setB .
  • After we finish printing the first element of setAllSorted , setAll will be fully appreciated. There are no more links to setOne , setTwo and smaller sets, so all of them are now available for garbage collection. The first setAllSorted element setAllSorted also be restored.

Thus, theoretically, this code would store setAll in memory most of the time, while setAllSorted , setOne and setTwo are likely to occupy a constant space at any time. Depending on the implementation of f the same may be true for smaller sets.

+7
source

Source: https://habr.com/ru/post/905003/


All Articles