Parsing command line arguments

限于喜欢 提交于 2019-12-07 10:14:11

问题


I'm very confused with prolog, it's way different to any language I've ever used (many languages) How do I go about getting argv[0] from:

current_prolog_flag(argv, Argv),
write(Argv).

Now if I tried to type Argv[0] or Argv(0) or Argv<0> it fails.. this leaves me with no clue and very little help from the documentation.. it seems that they expect you to already be a prolog expert :D

Another question, how would I assign Argv[0] to a variable so I can print it later using "write" ?


回答1:


Prolog uses matching.

?- current_prolog_flag(argv, [File | Rest]).
File = 'C:\\Program Files\\pl\\bin\\swipl-win.exe',
Rest = ['--win_app'].

This matches a list with a head and the tail:

[Head | Tail]

Head is the first element and Tail is the rest of the list.

To get the last element, use:

?- current_prolog_flag(argv, Argv), append(_, [Last], Argv).
Argv = ['C:\\Program Files\\pl\\bin\\swipl-win.exe', '--win_app'],
Last = '--win_app'

To get help about functions like append:

apropos(append).



回答2:


You can use nth0 and nth1 (same as nth0, but starts counting elements from 1 instead of 0) predicates:

current_prolog_flag(argv, Argv),
nth0(0, Argv, Argument0), % get first argument
nth0(1, Argv, Argument1), % get second argument
write(Argument0).

Most often nth0(Index, List, Element) is used as follows:

% get element by index
nth0(1, [a, b, c, d], E) % E = b

% get index by element
nth0(I, [a, b, c, d], b) % I = 1

% enumerate elements with their corresponding indexes
List = [a, b, c, d],
forall(nth0(I, List, E), format('List[~w]=~w~n', [I, E])).
% example above prints    
List[0]=a
List[1]=b
List[2]=c
List[3]=d


来源:https://stackoverflow.com/questions/15725670/parsing-command-line-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!