2

If a function has a case that will result in returning the input as-is, is there anything to be gained by using a point-free id for that case?

Example:

-- First way, use some symbol as wildcard
myFunc :: Int -> SomeData -> SomeData
myFunc 0 _ = _
myFunc ...

-- Second way, point-free `id`. Is this more efficient?
myFunc :: Int -> SomeData -> SomeData
myFunc 0 = id
myFunc ...

One standard function where I thought this might be used is drop since drop 0 is effectively id. But if you look at the source code, it is not point free (there is drop 0 xs = xs ... you have to scroll down a little to see the definition; look for drop (I# n#) ls). I suspect it can't matter much if drop doesn't make use of it.

Edit: Actually it looks like equations with differing numbers of arguments is disallowed by the case-expansion method for translating multiple-equation function definitions.

So if you opted for this route, you'd have to make sure all the remaining equations for the function are also definable in the same point-free style -- which is highly unlikely for most functions.

Community
  • 1
  • 1
ely
  • 74,674
  • 34
  • 147
  • 228

1 Answers1

4

In GHC, there can be a difference. Which is better will depend on the situation. Specifically, a function is only inlined by the optimizer if it is "fully applied". So in the first formulation, if you were to do something like

fooThing (myFunc 0)

then (unless some other optimizations happen first), GHC will produce a closure representing myFunc 0 and then apply it once fooThing decides to do so. If you use your id-based implementation instead, GHC will translate the above to

fooThing id
dfeuer
  • 48,079
  • 5
  • 63
  • 167
  • Another place where I wonder about the difference is unit testing, or QuickCheck-like things. If you replace with `id` it might be possible to write a unit test that is more like a law: "`myFunc 0` doesn't change anything ever ..." or something like that, which could be proven via `id` but it's not clear to me what it would do in the other case. – ely Jan 19 '15 at 02:02