.. _search-order: ======================= Search order and memory ======================= A short program can describe a search that takes a lot of memory and time. Two things affect that cost: where the program makes its choices, and the order in which Sprite tries the alternatives. An alternative is one path through the choices of a program. This page shows each of the two with a small program. The place of a choice ===================== A search can cost much less when the program decides a choice first and then computes with the chosen value than when it computes with the choice still inside its data. The two programs below differ only in that. In ``Shared.curry``, ``oneOf [1 .. 12]`` is a choice among twelve numbers. ``run`` builds a list from the chosen number and takes its length twice. No list has a length both above and below zero, so the condition of ``run`` never holds and ``run`` has no value: .. code-block:: haskell oneOf :: [a] -> a oneOf (x:xs) = x ? oneOf xs big :: Int -> Int -> [Int] big n a = [a .. a + n] run :: Int -> Int run n = let a = oneOf [1 .. 12] w = big n a in if length w > 0 && length w < 0 then a else failed .. code-block:: python >>> import curry >>> curry.path.insert(0, '.') >>> Shared = curry.import_('Shared') >>> list(curry.eval(Shared.run(10))) [] ``run 10000`` builds lists of 10,001 numbers. That run stopped at a limit of 2 GB of address space after 75 seconds. This figure and the others of this section are for the default order of a search; the next section describes the orders. ``First.curry`` is ``Shared.curry`` with ``run`` replaced by two definitions. ``body`` is the computation, and ``run`` decides the choice before it calls ``body``. It does so with the operator ``$!``, which evaluates its argument before it applies the function; for an ``Int`` the result is the number: .. code-block:: haskell body :: Int -> Int -> Int body n a = let w = big n a in if length w > 0 && length w < 0 then a else failed run :: Int -> Int run n = body n $! oneOf [1 .. 12] ``run 10000`` has no value here either, and it ends after 1.0 seconds with a peak of 145 MB. The difference comes from pull-tabbing, the way Sprite evaluates a choice (:doc:`CurryPrimer/Semantics`). When a step needs a value and finds a choice, the choice moves up past that step, then past the step that waits for it, and so on to the root of the expression. There Sprite makes two alternatives, which share every part of the expression that the choice did not pass. In ``Shared.curry`` the choice ``a`` is inside the list. Every cell needs the bound ``a + n``, so every cell that ``length`` reads meets the choice. In the current alternative that choice was decided long before, but Sprite can tell only when the choice reaches the root. The ``length`` of the Prelude adds one per cell (``length (_:xs) = 1 + length xs``), so at cell *i* there are *i* additions waiting, and the choice moves up through a copy of each. The work therefore grows with the square of the length of the list. The copies stay in memory, because the alternative that waits still reaches them through the second ``length w``. In ``First.curry`` each choice reaches the root before the list exists, and ``body`` computes on a number. These rules follow for a program that searches: * Decide a choice before you build on it, with ``f $! choice`` or a ``case`` on the choice. The choice then reaches the root while little waits above it. * Keep a choice out of data that later steps share. ``$!`` evaluates only the outer form of its argument. For a number that is the whole value, but a choice inside a list or a tuple stays inside. Choose the parts first and build the structure from the chosen values. * Use an accumulator in a long traversal. ``length`` above keeps one addition waiting per cell, and a choice met at a cell moves up through all of them. With an accumulating length in place of ``length``, ``Shared.run 10000`` ends after 5 seconds but still peaks at 1.3 GB, because every cell still meets the choice and every move leaves a copy. So an accumulator shortens each move and does not replace the first two rules. * Force only what every result needs. If the program can produce a result without the forced value, and that value fails or does not end, the rewritten program loses the result. The order of a search ===================== Sprite keeps the open alternatives of a search in a queue. The interpreter flag ``search`` (:ref:`interpreter-flags`) selects how Sprite works through them: ``fair`` The alternatives that can run take turns, so a value is found even beside an alternative that never ends. This is the default, and it is the order of the Fair Scheme. Every open alternative is in the queue with the data it keeps, so memory grows with the width of the search. ``dfs`` The search goes depth-first. The left alternative runs first, to its end or until it waits for a free variable to be bound; a waiting alternative gives way and stays in the queue. The queue holds the alternatives beside the current path and the waiting ones. An alternative that never ends hides the values after it. A search that ends without an error finds the same values under both orders, but their sequence can differ. Under ``dfs`` the values come in the sequence of the alternatives, left first, with a waiting alternative later. Under ``fair`` the sequence depends on the schedule: .. code-block:: python >>> list(curry.eval(curry.parse('(0 ? 1) ? 2'), search='dfs')) [0, 1, 2] >>> sorted(curry.eval(curry.parse('(0 ? 1) ? 2'))) [0, 1, 2] Two things show the sequence and can therefore differ between the orders: the list that the I/O action ``values2list`` returns for a set, and the values that arrive before an error. For a search that ends, ``dfs`` can need much less memory than ``fair`` in about the same time. ``Ops.curry`` describes every list of seven operations, each one of ``A`` to ``F``, and keeps the lists with exactly three ``A``. It has 279,936 candidates and 21,875 values: .. code-block:: haskell data Op = A | B | C | D | E | F deriving (Eq, Show) op :: Op op = A ? B ? C ? D ? E ? F run :: Int -> Int -> [Op] run n acc = if n == 0 then (if acc == 3 then [] else failed) else let o = op in o : run (n-1) (if o == A then acc+1 else acc) main :: [Op] main = run 7 0 ========= ==== =========== Order Time Peak memory ========= ==== =========== ``fair`` 18 s 680 MB ``dfs`` 18 s 280 MB ========= ==== =========== Both runs took about 18 seconds, and the run under ``dfs`` used 400 MB less memory. ``curry.eval`` and ``curry.solve`` take the order of one evaluation as the keyword ``search``; without it they use the flag of the session: .. code-block:: python >>> Ops = curry.import_('Ops') >>> len(list(curry.eval(Ops.main, search='dfs'))) 21875 ``curry.reset(search='dfs')`` starts a new session with that order; import the modules again after it. The tools read the flag from the environment (``SPRITE_INTERPRETER_FLAGS=search:dfs sprite-exec Ops.curry -g main``), and the REPL takes ``:set search dfs``. For a search that is known to end, use ``dfs`` when the open alternatives take too much memory. Keep the fair order when an alternative may never end and must not hide the values of the others. You still need the rules of the first section under ``dfs``, where ``Shared.run 10000`` still stopped at the 2 GB limit, after 19 seconds, and ``First.run 10000`` ended after 1.5 seconds with a peak of 150 MB. The figures on this page are from one machine, measured with ``sprite-exec``. A time includes the start of the interpreter, and memory is the peak resident size. The runs under the fair order used ``SPRITE_ROTATION=steps:65536`` in place of the default rotation by time, so that they reproduce.