Q:

Compute next prime number in Haskell

I am trying to compute the next closest prime number after a number is entered with Haskell,
I have coded 2 functions isPrime and nextPrime 
Here is my code:
isPrime :: Int -> Bool
isPrime x   | x < 2          = False
        | otherwise      = prime (2:[3,4..(x-1)])
where 
    prime (y:z)
        | x < y ^ 2      = True
        | x `mod` y == 0 = False
        | otherwise      = prime z

nextPrime :: Int -> Int
nextPrime n | isPrime n == True = n
            | otherwise = nextPrime n
        where
            n = n + 1

The problem I have is that I get this error when I run it : * Exception: "<<"loop">>"
I don't know what's wrong, is it an infinite loop?

A:

You cannot change the value of variables in Haskell. This means that you cannot execute
n = n + 1

since that would change the value of n. In Haskell, n is a name that always refers to the same value inside the function it is used. If n starts out as 3, n will always be 3. You could do,
next = n + 1

and then also change
| otherwise = nextPrime n

into
| otherwise = nextPrime next

This will not change the value of any variable, but instead create a new variable with the new value – something you often do in Haskell!

A:

Just change the definition of nextPrime to
nextPrime :: Int -> Int
nextPrime n | isPrime n = n   -- don't need to compare to True here
            | otherwise = nextPrime (n+1)

You generate an infinite regress when you try to define n = n + 1, as the runtime would attempt to expand this as
n =   n + 1
  =  (n + 1) + 1
  = ((n + 1) + 1) + 1
  = ...

Fortunately, the compiler is able to detect this kind of infinite regress and warn you about it!

