tadashi
tadashi

Reputation: 91

Prolog: If a float is input, output prints out error

I'm new to SWI-prolog and I'm having trouble with my code. I want it to determine if the input is a multiple of 5 and not an even number but if it's not an integer it should print out an error message. So far I have this but it's not printing out the error message and instead it's just telling me it's a type error.

MultOf5(N) :- 
0 is N mod 5, \+ 0 is N mod 2. 
MultOf5(Other) :-
N is Other,
print("ERROR: The given parameter is not an integer").

It's printing out this when I input:

?-Multof5(4.7)
 Singleton variables: [N]
 mod/2: Type error: `integer' expected, found `4.2' (a float)

Please let me know where I'm going wrong and what I could do to fix this. It's saying I have a singleton variable too. Thanks.

Upvotes: 0

Views: 975

Answers (1)

lurker
lurker

Reputation: 58284

Noted issues in the posted code:

  • In Prolog, a predicate cannot start with a capital letter. So MultOf5(N) ... is invalid. Judging from the messages you are showing, I assume that's not how your code is really written.
  • multOf5(Other) ... only refers to N one time, and it's not otherwise used. That's what generates a singleton warning.
  • mod, as you know, operates on integers, and your first clause attempts mod on the value 4.2, which will fail. You can use integer(N) which succeeds if N is integer.

I would prefer the positive 1 is N mod 2 over the negative \+ 0 is N mod 2.

oddMultOf5(N) :-
    (   integer(N)
    ->  0 is N mod 5,
        1 is N mod 2
    ;   print("ERROR: The given parameter is not an integer")
    ).

Upvotes: 3

Related Questions