buydadip
buydadip

Reputation: 9437

Haskell - "lacks an accompanying binding" for recursive function

I have the following function:

tempFunc :: Int-> Int-> Int
tempFunc x y
    | y == 0 = 0
    | x `mod` y == 0 = y + tempFunc x (y-1)
    | otherwise = y-1

Its purpose is to recursively sum all the factors of a number together. I want to eliminate the need for the second parameter y (since y is equal to x), so I implemented the function in the following way

tempFunc :: Int-> Int-> Int
sumFactor num = tempFunc num num
    where
        tempFunc x y
        ...

But I get the following error:

The type signature for ‘tempFunc’ lacks an accompanying binding

This type of error, I noticed, arises when the type definitions are incorrect. But I cannot figure out what is wrong with my type definitions, since the first excerpt works.

Upvotes: 2

Views: 497

Answers (1)

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

The type signature for a function has to be in the same scope as the function itself. If you want to add a type signature to a function inside a where clause (which is usually not done, but sometimes makes sense) you have to put it in the where clause itself:

sumFactor num = tempFunc num num
    where
        tempFunc :: Int-> Int-> Int
        tempFunc x y
            | y == 0 = 0
            | x `mod` y == 0 = y + tempFunc x (y-1)
            | otherwise = y-1

Upvotes: 11

Related Questions