How to resolve the algorithm Return multiple values step by step in the Mercury programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Return multiple values step by step in the Mercury programming language

Table of Contents

Problem Statement

Show how to return more than one value from a function.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Return multiple values step by step in the Mercury programming language

Source code in the mercury programming language

:- module addsub.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

main(!IO) :-
    command_line_arguments(Args, !IO),
    filter_map(to_int, Args, CleanArgs),
    (length(CleanArgs, 2) ->
        X = det_index1(CleanArgs,1),
        Y = det_index1(CleanArgs,2),
        addsub(X, Y, S, D),
        format("%d + %d = %d\n%d - %d = %d\n", 
               [i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO)
    ;
        write_string("Please pass two integers on the command line.\n", !IO)
    ).

:- pred addsub(int::in, int::in, int::out, int::out) is det.
addsub(X, Y, S, D) :-
    S = X + Y,
    D = X - Y.

:- end_module addsub.

:- func addsub(int, int) = {int, int}.
addsub(X, Y) = { X + Y, X - Y }.

        {S, D} = addsub(X, Y),

:- module addsub.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

:- type my_result ---> twin(int, int).

main(!IO) :-
    command_line_arguments(Args, !IO),
    filter_map(to_int, Args, CleanArgs),
    (length(CleanArgs, 2) ->
        X = det_index1(CleanArgs,1),
        Y = det_index1(CleanArgs,2),
        twin(S, D) = addsub(X, Y),
        format("%d + %d = %d\n%d - %d = %d\n",
               [i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO)
    ;
        write_string("Please pass two integers on the command line.\n", !IO)
    ).

:- func addsub(int, int) = my_result.
addsub(X, Y) = twin(X + Y, X - Y).

:- end_module addsub.

  

You may also check:How to resolve the algorithm Substring/Top and tail step by step in the AWK programming language
You may also check:How to resolve the algorithm Sudoku step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bead sort step by step in the Clojure programming language
You may also check:How to resolve the algorithm Morse code step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Stream merge step by step in the C# programming language