Take the 2-minute tour ×

Composition is very normal in Haskell, but I just know that I can define special behavior of a composite function, says

Prelude> (floor . sqrt) (10^55)
Prelude> let (floor . sqrt) n | n < 2 = n | otherwise = head $ dropWhile (\x -> x^2 > n) $ iterate (\x -> (x + n `div` x) `div` 2) (n `div` 2)
Prelude> (floor . sqrt) (10^55)

The result from special define function is correct (because of floating point error in the first one).

Now I want to do the same inside .hs file, like

(floor . sqrt) n
    | n < 2 = n

main = do
    print $ (floor . sqrt) (10^55)

This time ghc yelling at me

Ambiguous occurrence `.'
It could refer to either `Main..', defined at me.hs:1:8
                      or `Prelude..',
                         imported from `Prelude' at me.hs:1:1
                         (and originally defined in `GHC.Base')

So does it possible to define function like this in .hs file? (Define it inside main with let is okey, however).

share|improve this question
You can't do it. (floor . sqrt) n treats floor and sqrt as variables, not functions, so this should work for all functions, which happen to be called floor and sqrt in this definition. Might as well have said (g . f) n. As for your ad-hoc specialization, this is not possible in Haskell, you'll have to get what you need some other way. –  luqui Apr 18 '13 at 18:06

2 Answers 2

up vote 13 down vote accepted

First of all, your example in GHCi is not defining a special composition of floor and sqrt. Instead, it's defining an operator (.) which takes three arguments named floor, sqrt, and n and hides the existing standard function named (.).

You then apply your new function to the standard library functions floor and sqrt, which become the parameters with the same names in your new (.) function.

The error you get is because a top-level definition does not automatically hide the existing definition, and anyway that's clearly not what you actually want to do.

Now, you can certainly define an entirely new function (hopefully with its own name, as in groovy's answer) to do your specialized floor . sqrt function, but there's no way in Haskell itself to define it as a specialized version of the existing functions.

What you might be thinking of, and is possible, is using compiler pragma rewrite rules in GHC to automatically replace specific expressions with equivalent, improved versions. You should be careful that your rewritten form gives the same answer as what it replaces, though. Otherwise you're risking some really baffling debugging sessions.

share|improve this answer

How about this?

floorSqrt n
    | n < 2     = n

main = do
    print $ floorSqrt (10^55)
share|improve this answer
I just want to experimental some concept, that is usual way I'am doing right now. –  neizod Apr 18 '13 at 18:25

Your Answer


