简体   繁体   中英

How do I combine rules and facts from a PROLOG program into a list?

Im trying to find the list of all release dates of all intel processors. It should look like this

[1993, 1976, 1974, 1971]

Currently I can only create a list with 1 entry like this

setof(Y,released(pentium,Y),S1) which gives me [1993].

prozessor(i4004).
prozessor(i8080).
prozessor(z80).
prozessor(i8086).
prozessor(a486).
prozessor(pentium).
prozessor(k5).
intel([i4004,i8080,i8086,pentium])
zylog([z80]).
amd([a486,k5]).

released(i4004, 1971).
released(i8080, 1974).
released(z80,1976).
released(i8086,1976).
released(a486,1991).
released(pentium,1993).
released(k5,1996).

influence(i4004,i8080).
influence(i8080,i8086).
influence(i8086,pentium).
influence(i8080,z80).
influence(i8086,a486).
influence(a886,k5).

You can collect the set of all Intel processor release years like this:

setof(Year, intel_release_year(Year), IntelReleaseYears).

For this you must define intel_release_year/1 . Given your definitions, this could look like this:

intel_release_year(Year) :-
    intel(IntelProcessors),
    member(Processor, IntelProcessors),
    released(Processor, Year).

Note that facts of the form

somepredicate([a, b, c]).

are not necessarily the best possible style. It is often better to use separate facts for the individual objects, rather than grouping them in a list:

somepredicate(a).
somepredicate(b).
somepredicate(c).

In your example this would be:

intel(i4004).
intel(i8080).
intel(i8086).
intel(pentium).

and then the definition of intel_release_year/1 doesn't need to use member/2 anymore:

intel_release_year(Year) :-
    intel(IntelProcessor),
    released(IntelProcessor, Year).

In either case, you get:

?- setof(Year, intel_release_year(Year), IntelReleaseYears).
IntelReleaseYears = [1971, 1974, 1976, 1993].

(Knowing some commenters here, I expect that some might insist that I mention that there is another, strictly inferior way of using setof/3 . So I mentioned it. Do not use setof/3 in that different, strictly inferior way.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM