0
votes

I am making calculating 2^(n-1) mod n. I had a problem with Haskell.

parse error (possibly incorrect indentation or mismatched brackets)
  |
5 |     | (mod e 2 == 0) = md (mod b*b m) (div e 2) m r
  |     ^

But the problem is I don't know what is the problem

modf :: Int -> Int
modf n = md 2 (n-1) n r
    where
    md b e m r
    | (mod e 2 == 0) = md (mod b*b m) (div e 2) m r
    | otherwise = md (mod b*b m) (div e 2) m (mod r*b m)
1
You need to indent the pipe characters (|) with at least one space - Willem Van Onsem
Now the error however says that you never defined r (which is indeed correct) - Willem Van Onsem

1 Answers

2
votes

The main problem is that the indentation level of the guards is the same as the md function itself). You need to indent it by at least one space:

modf :: Int -> Int
modf n = md 2 (n-1) n r
    where
    md b e m r
        | (mod e 2 == 0) = md (mod b*b m) (div e 2) m r
        | otherwise = md (mod b*b m) (div e 2) m (mod r*b m)

Now the syntax error has been resolved, but it will raise an error on the fact that you use r, but never defined r.

We can implement this more elegantly by:

import Data.Bits(shiftR)

modf :: Int -> Int
modf m = go 2 (m-1)
    where go k 1 = k
          go k n | even n = go2
                 | otherwise = mod (go2 * k) m
              where go2 = go (mod (k*k) m) (shiftR n 1)