Smit Patel
Smit Patel

Reputation: 39

Writing a function/method containing conditionals in prolog

I'm new to Prolog, and so I came here to know and learn about this new language from you fine people.

I'm writing a function 'decision' which has 3 parameters I=income, D= dependents, S=savings, and I'm trying to find out if the person should invest in savings, stocks, or both.

Here, is my code...

decision(I, D, S) :-
    Minincome is 9000 + 2500*D,
    Minsaving is D*3000,

    saving(S, Minsaving) :- S < Minsaving, write('You should invest your money into savings. ').
    saving(S, Minsaving) :- S >= Minsaving,
    income(I, Minincome) :- I > Minincome, write('You should try to invest in NYSE stock market. ');
    income(I, Minincome) :- I =< Minsaving, write('You should invest your money into both, saving and stock market. ').

What I'm trying to do is if person has saving less than Minsaving, than he should invest in savings,

else if a person has savings greater than Minsaving and income greater than Minincome, than he should invest in stock market,

else if a person has savings greater than Minsaving and income less than Minincome, than he should invest in stock market as well as savings.

I hope I was clear. Thanks

Upvotes: 0

Views: 47

Answers (1)

Isabelle Newbie
Isabelle Newbie

Reputation: 9378

You're on the right track, but you have some typos, and you must close the definition of your decision predicate with a period . before you can define new predicates. There is no nesting of predicate definition within other predicate definitions in Prolog.

Here are some cleaned up versions of your helper predicates:

write_saving(S, Minsaving) :-
    S < Minsaving,
    write('You should invest your money into savings. ').
write_saving(S, Minsaving) :-
    S >= Minsaving.
    
write_investment(I, Minincome) :-
    I > Minincome,
    write('You should try to invest in NYSE stock market. ').
write_investment(I, Minincome) :-
    I =< Minincome.

Note that every clause ends in a period ., not in a comma or semicolon or anything else.

And your completed decision predicate can call these:

decision(Income, Dependents, Savings) :-
    Minincome is 9000 + 2500 * Dependents,
    Minsaving is Dependents * 3000,
    write_saving(Savings, Minsaving),
    write_investment(Income, Minincome).

Examples:

?- decision(8000, 1, 2000).
You should invest your money into savings. 
true .

?- decision(17000, 1, 4000).
You should try to invest in NYSE stock market. 
true .

?- decision(17000, 1, 2000).
You should invest your money into savings. You should try to invest in NYSE stock market. 
true .

Note that there is no special case for printing "you should save AND you should invest in the stock market". Since both write_saving AND write_ivestment are executed, their outputs combine. If you want to treat this differently, you must write a predicate that has both a Minsaving and a Minincome parameter and compare accordingly.

Upvotes: 1

Related Questions