Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: Different behaviour of single and double quotes

I'm quite new to Prolog and I stumbled on something that I don't understand.

This is my code:

:- dynamic user/3.
user('id', 'Name', 20).

changeAge(Id, NewAge) :-
   user(Id, Name, _),
   retract(user(Id,_,_)),
   assert(user(Id,Name,NewAge)).

To update user information in the database, changeAge/2 performs these three steps:

  1. Lookup a right record, using user/3.
  2. Remove one matching record from the database, using retract/1.
  3. Insert a new updated record into the database, using assert/1.

This is my console output:

1 ?- user('id', _, Age).
Age = 20.

2 ?- changeAge('id', 25).
true.

3 ?- user('id', _, Age).
Age = 25.

4 ?- changeAge("id", 30).
false.

5 ?- user('id', _, Age).
Age = 25.

Why do single quotes give me true (line 2) when double quotes give me false (line 4)?

like image 451
Ionut Avatar asked Sep 03 '25 02:09

Ionut


1 Answers

TL;DR1: Read this answer to the question "What is the difference between ' and " in Prolog?".

TL;DR2: The goal 'id' = "id" succeeds iff the Prolog flag double_quotes is set to atom.

The Prolog flag double_quotes can be set at runtime using set_prolog_flag/2:

  • ?- set_prolog_flag(double_quotes, chars).

    ?- 'id' = "id".
    false.
    
  • ?- set_prolog_flag(double_quotes, codes).

    ?- 'id' = "id".
    false.
    
  • ?- set_prolog_flag(double_quotes, atom).

    ?- 'id' = "id".
    true.
    

For more information read the SICStus Prolog manual page on "Strings as lists"!

like image 82
repeat Avatar answered Sep 07 '25 13:09

repeat