[Haskell-cafe] Re: How to make code least strict?

Ryan Ingram ryani.spam at gmail.com
Mon Jan 19 15:27:18 EST 2009


On Mon, Jan 19, 2009 at 9:10 AM, ChrisK <haskell at list.mightyreason.com> wrote:
> Consider that the order of pattern matching can matter as well, the simplest
> common case being zip:
>
> zip xs [] = []
> zip [] ys = []
> zip (x:xs) (y:ys) = (x,y) : zip xs ys

If you are obsessive about least-strictness and performance isn't a
giant concern, this seems like a perfect use for Conal's unamb[1]
operator.

zipR xs [] = []
zipR [] ys = []
zipR (x:xs) (y:ys) = (x,y) : zip xs ys

zipL [] ys = []
zipL xs [] = []
zipL (x:xs) (y:ys) = (x,y) : zip xs ys

zip xs ys = unamb (zipL xs ys) (zipR xs ys)

This runs both zipL and zipR in parallel until one of them gives a
result; if neither of them is _|_ they are guaranteed to be identical,
so we can "unambiguously choose" whichever one gives a result first.

  -- ryan

[1] http://conal.net/blog/posts/functional-concurrency-with-unambiguous-choice/


More information about the Haskell-Cafe mailing list