anonymous
anonymous

Reputation: 313

Got three "Variable not in scope" errors in my Haskell code while doing module expressions for guards

I have the following Haskell code with guards which are intended to print the following Strings when I entered a number for my function, meaning when it is divided by either 2, 3, or 5 it was intended to print a string containing the number in Spanish, otherwise printing "Nada".

compositeNumber::Integer -> String
compositeNumber x 
    |(x % 2 == 0) = "Dos"
    |(x % 3 == 0) = "Tres"
    |(x % 5 == 0) = "Cinco"
    |otherwise = "Nada"
    
main = print$ compositeNumber 4;

However, when I went to run my code, I got this error.

main.hs:3:9: error:
    Variable not in scope: (%) :: Integer -> Bool -> Bool
  |
3 |     |(x % 2 == 0) = "Dos"
  |         ^

main.hs:4:9: error:
    Variable not in scope: (%) :: Integer -> Bool -> Bool
  |
4 |     |(x % 3 == 0) = "Tres"
  |         ^

main.hs:5:9: error:
    Variable not in scope: (%) :: Integer -> Bool -> Bool
  |
5 |     |(x % 5 == 0) = "Cinco"
  |         ^

I am still new to Haskell and I am currently learning it, and there are probably some things in the language which are unfamiliar to me. I would really appreciate it if you would help me find out how to fix this error!

Upvotes: 0

Views: 117

Answers (1)

bradrn
bradrn

Reputation: 8467

Haskell does not use % for modulus. Use the rem or mod functions instead. That is, replace expressions like x % 2 with rem x 2 or x `rem` 2.

(As for the difference between rem and mod, my understanding is that they differ mostly with respect to their behaviour with negative numbers. When you only need to deal with positive numbers, rem is usually recommended as it is slightly faster.)

Upvotes: 3

Related Questions