简体   繁体   English

在Prolog中打印出List的元素

[英]Printing out elements of List in Prolog

I've got a list, X, that contains three elements; 我有一个包含三个元素的列表X; ID, Name, and Grade. ID,名称和成绩。 All taken from user input 全部取自用户输入

read_student_info([A, B, C]),
nl, nl, menu([[A, B, C] | X]).

read_student_info([A, B, C]) :-
  write('\tStudent ID: '),
  read(A),
  write('\tStudent Name: '),
  read(B),
  write('\tStudent Grade: '),
  read(C).

Now, I want to display the elements from the list. 现在,我想显示列表中的元素。 So if I have a student whose ID = 3, Name = Tom, Grade = 78. That's what I'd like to print out. 所以,如果我有一个ID为3的学生,姓名= Tom,等级= 78.这就是我要打印的内容。 The current function I've been fooling around with is this: 我一直在搞的当前功能是这样的:

show_records(X) :-
  X = [A | B],
  A = [C | D],
  id = write(C),
  name = format("~s", [B]),
  grade = write(D),
  show_records(B).

However I'll be the first to admit I have almost no clue what I'm doing. 但是我会第一个承认我几乎不知道我在做什么。 Any help would be very appreciated! 任何帮助将非常感谢!

just suggesting a way to cleanup: 只是建议一种清理方法:

show_records([]).
show_records([A|B]) :-
  format('ID = ~w\tName = ~w\tGrade = ~w~n',A),
  show_records(B).

test: 测试:

?- show_records([[1,abel,10], [2,goofy,4]]).
ID = 1  Name = abel Grade = 10
ID = 2  Name = goofy    Grade = 4

clearly, tabs are not optimal, but simple to use 很明显,标签不是最佳的,但使用简单

I have it figured out, mostly anyway. 无论如何,我已经想通了。 Here is my revision. 这是我的修订版。

show_records(X) :-
X = [A | B],
write('\tID = '),
A = [C | D],
write(C),
write('\tName = '),
D = [E | F],
format("~s", [E]),
write('\tGrade = '),
F = [G | H],
write(G),
nl,
show_records(B).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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