user2069328
user2069328

Reputation: 71

Haskell Where Syntax

wondering what's syntactically wrong with this function?

isPrime :: Int -> Bool
isPrime a = go a (a - 1)
        where 
        go a b 
        |b == 1 = True
        |a / b == 0 = False
        |otherwise = isPrime a (b - 1)

Just a simple function to determine whether a number is prime or not, thanks.

isPrime :: Int -> Bool
isPrime a = go a (a - 1)
    where 
        go a b 
            |b == 1 = True
            |a / b == 0 = False
            |otherwise = isPrime a (b - 1)

I now have this, but still get compilation errors?

Upvotes: 0

Views: 1820

Answers (1)

user2556165
user2556165

Reputation:

The Haskell programs have to be well indented! That is how to indent your program well:

isPrime :: Int -> Bool
isPrime a = go a (a - 1)
  where -- indent before `where` 
    go a b -- indent after `where`'s indent
      | b == 1     = True
      | a / b == 0 = False
      | otherwise  = isPrime a (b - 1)

If you'll edit your code in this way, you'll still get error when compile it. The reason is because you are trying to call isPrime with two arguments in go's body, but it takes only one (that is stated in isPrime's annotation). To edit it, you just need to replace isPrime a (b - 1) to go a (b - 1).

After that edit, you'll get another error when compile the program: a stated to be Int, but you are applying fractional division to it with / operator. For Int type only integer division is allowed:

a `div` b == 0 = False

But you don't need to apply that division at all. To state whether the one number can be divided by another you should take a rest of division and compare it with zero:

a `mod` b == 0 = False

So, final program will be:

isPrime :: Int -> Bool
isPrime a = go a (a - 1)
  where -- indent before `where` 
    go a b -- indent after `where`'s indent
      | b == 1         = True
      | a `mod` b == 0 = False
      | otherwise      = go a (b - 1)

Upvotes: 1

Related Questions