# Visual Prolog

## Задача 1

С клавиатуры вводятся два целых числа.

Вывести на экран их сумму.

```
implement main
    open core, console

clauses
    run() :-
        stdio::write("Input A:"),
        nl,
        SA = stdio::readline(),
        stdio::write("Input B:"),
        nl,
        SB = stdio::readline(),
        A = toTerm(SA),
        B = toTerm(SB),
        K = A + B,
        stdio::write("Result: ", K),
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 2

С клавиатуры вводятся два целых числа.

Необходимо провести сравнение введённых чисел.

```
implement main
    open core, console

clauses
    run() :-
        A = toTerm(stdio::readline()),
        B = toTerm(stdio::readline()),
        if A > B then
            stdio::write("A: "),
            stdio::write(A)
        elseif A < B then
            stdio::write("B: "),
            stdio::write(B)
        else
            stdio::write("A: ", A),
            stdio::write(" and "),
            stdio::write("B: ", B)
        end if,
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 3

Проверить принадлежность числа определённому отрезку.

Использовать логическое "И".

```
implement main
    open core, console

clauses

    run() :-
        X = toTerm(stdio::readline()),
        A = 100,
        B = 200,
        if A <= X and X <= B then
            write("YES")
        else
            write("NO")
        end if,
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 4

Вывести на экран все целые числа на определённом отрезке.

Найти сумму целых чисел на определённом отрезке.

Использовать циклы и глобальные переменные.

```
implement main
    open core, console

class facts
    i : integer := 0.
    s : integer := 0.
    a : integer := 0.
    b : integer := 0.
    stop : boolean := false.

clauses
    run() :-
        a := toTerm(stdio::readline()),
        b := toTerm(stdio::readline()),
        stop := false,
        i := a,
        s := 0,
        nl,
        std::repeat(),
            if i <= b then
                s := s + i,
                stdio::write("Number: ", i),
                nl,
                i := i + 1
            else
                stop := true
            end if,
            stop = true,
            !,
        nl,
        stdio::write("Summa: "),
        stdio::write(s),
        nl,
        _ = readLine()
        or
        succeed().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 5

Дана база фактов.

Необходимо получить всех мальчиков старше определённого возраста.

Вывести их количество на экран.

```
implement main
    open core, console

class facts
    k : integer := 0.
    manAge : (string, integer).
    boy : (string).

clauses
    boy("maxim").
    boy("george").
    boy("piter").
    manAge("maxim", 25).
    manAge("george", 17).
    manAge("piter", 22).
    manAge("nina", 27).
    manAge("ann", 14).

    run() :-
        stdio::write("Adult boys:"),
        nl,
        k := 0,
        nl,
        foreach manAge(M, A) and boy(M) and A > 20 do
            stdio::write("Man: ", M),
            stdio::write("  "),
            stdio::write("Age: ", A),
            k := k + 1,
            nl
        end foreach,
        nl,
        stdio::write("Number: ", k),
        nl,
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 6

С клавиатуры вводятся два целых числа.

Необходимо получить наибольшее из двух чисел.

Также надо найти сумму введённых чисел.

При решении задачи использовать вспомогательные предикаты.

```
implement main
    open core, console

class predicates
    sum : (integer, integer, integer [out]).
    big : (integer, integer, integer [out]).

clauses
    sum(A, B, C) :-
        C = A + B.

    big(A, B, C) :-
        if A > B then
            C = A
        else
            C = B
        end if.

    run() :-
        AA = toTerm(stdio::readline()),
        BB = toTerm(stdio::readline()),
        sum(AA, BB, X),
        big(AA, BB, Y),
        nl,
        write("Summa: ", X),
        nl,
        write("Biggest: ", Y),
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 7

Дан текстовый файл.

Необходимо осуществить посимвольное чтение из файла.

Вывести считанные символы на экран.

```
implement main
    open core, console

class facts
    n : integer := 0.

clauses
    run() :-
        n := 0,
        F1 = inputStream_file::openFile("aaa.txt", stream::unicode()),
        std::repeat(),
            S = F1:readChar(),
            n := n + 1,
            write(n, ")  ", S),
            nl,
            F1:endOfStream(),
            !,
        F1:close(),
        nl,
        _ = readLine()
        or
        succeed().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 8

Создать текстовый файл.

Добавить содержимое в файл.

```
implement main
    open core, console

class facts
    s : string := "".

clauses
    run() :-
        F2 = outputStream_file::create("bbb.txt"),
        s := "abc",
        F2:write(s),
        s := "xyz",
        F2:write(s),
        F2:nl,
        s := "012345",
        F2:write(s),
        F2:close(),
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 9

Создать динамическую базу фактов.

Хранить данные в виде ключ - значение.

```
implement main
    open core, console

class facts
    store : (string, integer).

class predicates
    printStore : ().
    saveKeyValue : (string, integer).

clauses
    saveKeyValue(K, V) :-
        if retract(store(K, _)) then
        end if,
        assert(store(K, V)).

    printStore() :-
        write("Content"),
        nl,
        foreach store(K, V) do
            write(K, " : ", V),
            nl
        end foreach,
        nl.

    run() :-
        saveKeyValue("maxim", 12),
        saveKeyValue("alex", 17),
        saveKeyValue("george", 25),
        printStore(),
        saveKeyValue("maxim", 200),
        saveKeyValue("alex", 300),
        saveKeyValue("george", 400),
        printStore(),
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```

## Задача 10

Хороший мальчик: хороший + мальчик.

Необходимо формализовать данную информацию и выполнить проверки.

Факты: **boy** и **good**.

Правило: **goodBoy**.

```
implement main
    open core, console

class facts
    boy : (string).
    good : (string).

class predicates
    goodBoy : (string [out]) nondeterm.

clauses
    goodBoy(X) :-
        boy(X),
        good(X).

    boy("maxim").
    boy("george").
    boy("alex").
    boy("oleg").
    good("nina").
    good("ann").
    good("alex").
    good("maxim").

    run() :-
        foreach goodBoy(Y) do
            write(Y),
            nl
        end foreach,
        nl,
        _ = readLine().

end implement main

goal
    console::runUtf8(main::run).
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maxim218.gitbook.io/prolog/visual-prolog.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
