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.

4

1 回答 1

14

Haskell 实现不记忆函数调用。

Haskell 编译器(如 GHC)确实会进行常见的子表达式消除,但存在一些限制。

如有疑问,请分享结果。

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

但是你有一个类型错误,因为 g' 不能同时是布尔值和可能。

但最好写成:

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

仅在一个分支中计算和共享结果。

于 2013-03-01T23:08:03.480 回答