0

If I have a function like the following

f x = if g x /= Nothing then g x else False

will g be called twice in f or does Haskell 'cache' the result of g x after the first instance for possible later use in the same line? I'm trying to optimise some code and I don't know if functions in the style of the one above are twice as computationally expensive as I want them to be.

Thanks in advance.

1
  • Also, whether things occur on the same line is irrelevant. It does affect the syntax, i.e. where a block starts and ends (which you can always write explicitly using { }), but other than that it does not affect anything. Commented Mar 2, 2013 at 18:21

1 Answer 1

13

Haskell implementations do not memoize function calls.

Haskell compilers such as GHC do do common subexpression eliminiation but there are limitations.

If in doubt, share the result.

f x = if g' /= Nothing then g' else False
    where g' = g x

But you have a type error, since g' can't be both a boolean and a Maybe.

But better written as:

f x = case g x of
          Nothing -> ..
          Just _  -> ..

to compute and share the result in one branch only.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. That explains things perfectly. And yes, I was bit hasty in writing that example function.
How do you know that g' cannot be both a Boolean and a Maybe? Just for example, g could be read, and the original function would typecheck ...
Ok, it could be instances of an overloaded g :). But \f g x -> if g x /= Nothing then g x else False isn't going to fly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.