`seq` on partially applied functions
Asked Answered
M

2

5

Lets say I have the following:

f :: a -> b -> c
g :: b -> c
g = f 10

Now lets say f is actually:

f x y = f1 x + y

Would:

g `seq` ...

actually evaluate f1 10, so later when running

g 9

it's actually just a simple addition?

If not, is there a way to "evaluate" parts of a partially applied function?

I'm looking for a generic solution, one that doesn't depend on knowing how f and g work.

Murton answered 16/4, 2012 at 7:51 Comment(0)
P
3

seq is shallow:

Prelude> let f1 = undefined
Prelude> let f = \x -> \y -> f1 x + y
Prelude> let g = f 10
Prelude> g `seq` 1
1
Prelude> g 9
*** Exception: Prelude.undefined
Prelude>

I'd take a look at Control.DeepSeq: http://hackage.haskell.org/packages/archive/deepseq/1.2.0.1/doc/html/Control-DeepSeq.html

Proponent answered 16/4, 2012 at 8:15 Comment(2)
I doesn't look like I can apply deepseq to functions.Murton
No, it looks like it only applies to data structures that take DeepSeq into account. Not a solution to your problem as stated.Proponent
A
9

No, it will not, because in general, the choice of right hand side for f might depend on y. If you want to share the result of f1 x between calls to g, you would have to write f like this:

f x = let z = f1 x in \y -> z + y

Of course, due to laziness this will not evaluate f1 x until the first time g is called. To have g `seq` ... force evaluation of f1 x, you would have to write:

f x = let z = f1 x in z `seq` (\y -> z + y)
Atronna answered 16/4, 2012 at 8:18 Comment(0)
P
3

seq is shallow:

Prelude> let f1 = undefined
Prelude> let f = \x -> \y -> f1 x + y
Prelude> let g = f 10
Prelude> g `seq` 1
1
Prelude> g 9
*** Exception: Prelude.undefined
Prelude>

I'd take a look at Control.DeepSeq: http://hackage.haskell.org/packages/archive/deepseq/1.2.0.1/doc/html/Control-DeepSeq.html

Proponent answered 16/4, 2012 at 8:15 Comment(2)
I doesn't look like I can apply deepseq to functions.Murton
No, it looks like it only applies to data structures that take DeepSeq into account. Not a solution to your problem as stated.Proponent

© 2022 - 2024 — McMap. All rights reserved.