eaer
eaer

Reputation: 11

Prolog - New list with positive, negative and "0" elements with 1, -1, 0 respectively in relation to input list

I'm working on a prolog problem where I have an input list of positive, negative and "0" numbers. I have to create and then output another list in relation to the first where each positive, negative and "0" number is replaced with a "1", "-1", and "0" respectively.

I have started on something that accepts a list and then replaces each element that is positive then negative and then "0" but I don't think it is working correctly.

replace(_, _, [], []).
replace(O, 1, [O|T], [1|T2]) :- H = 1 replace(O, 1, T, T2).
replace(O, -1, [O|T], [-1|T2]) :- H = -1 replace(O, -1, T, T2).
replace(O, 1, [O|T], [0|T2]) :- H = 0 replace(O, 0, T, T2).

Thanks for any help!

Upvotes: 1

Views: 1008

Answers (3)

false
false

Reputation: 10132

..., maplist(\N^S^(S is sign(N)), In, Out), ...

Upvotes: 1

CapelliC
CapelliC

Reputation: 60034

you can simplify a lot your code

replace([], []).
replace([O|T], [R|T2]) :- convert(O,R), replace(T, T2).

convert(N,1) :- N > 0.
convert(N,0) :- N =:= 0.
convert(N,-1) :- N < 0.

when you have convert/2, you can do

?- maplist(convert, In, Out).

and forget about replace/2

Upvotes: 1

vmg
vmg

Reputation: 4326

You have the right intuition, but you got confused some with your parameters. What do you meant to do with H? Also, remember to separate statements with a comma, otherwise you're getting syntax errors. See if this suits you:

replace([],[]).
replace([0|T],[0|T2]):- replace(T,T2).
replace([P|T],[1|T2]):- P > 0, replace(T,T2).
replace([N|T],[-1|T2]):- N < 0, replace(T,T2).

This is a general form for replacing-elements-in-lists. You can change the checks and include additional clauses to define how to deal with non-numeric input, for example.

Upvotes: 0

Related Questions