-1

How can I write data to CSV file from the prolog code below?

Thanks,

SB

run:-
   member(A,[a,b,c,d,e]),
   member(B,[1,2,3,4,5,6]),
   write(A),write(' '),write(B),nl,
   fail.
run.
false
  • 10,264
  • 13
  • 101
  • 209
  • possible duplicate of [Prolog - How to write all prolog answers to .txt file?](http://stackoverflow.com/questions/18674731/prolog-how-to-write-all-prolog-answers-to-txt-file) – Eugene Sh. Dec 05 '14 at 17:01
  • 1
    @EugeneSh. I'm not sure whether that is a full duplicate. This question inquires into a specific format, i.e. CSV, that is not mentioned in the other question. – Wouter Beek Dec 05 '14 at 18:07
  • @WouterBeek Well, adding coma instead of space and changing the file extension? Does it make such a difference? – Eugene Sh. Dec 05 '14 at 18:09
  • 1
    @EugeneSh.: CSV it's a standard format, and so easy to do right – CapelliC Dec 05 '14 at 19:23

1 Answers1

2

Simple solution

Since you are using SWI-Prolog, you can use the CSV library.

?- use_module(library(csv)).
?- findall(row(A,B), (member(A, [a,b,c,d,e]), member(B, [1,2,3,4,5])), Rows), csv_write_file('output.csv', Rows).

As you can see, I do this in two steps:

  1. I create terms of the form row(A, B).
  2. Then I hand those terms to csv_write_file/2 which takes care of creating a syntactically correct output file.

Non-standard separators

In your question you are not writing a comma between A and B but a space. If you really want to use the space as a separator you can set this as an option:

csv_write_file('output.csv', Rows, [option(separator(0' )])

'Unbalanced' arguments

Also, in your question you have more values for B than for A. You can write code that handles this, but there are several ways in which this can be dealt with. E.g., (1) you can fill missing cells with nill; (2) you can throw an exception if same_length(As, Bs) fails; (3) you can only write the 'full' rows:

length(As0, N1),
length(Bs0, N2),
N is max(N1, N2),
length(As, N),
append(As, _, As0),
length(Bs, N),
append(Bs, _, Bs0),
Wouter Beek
  • 3,307
  • 16
  • 29