【问题标题】:Prolog convert list of string to list of numbersProlog将字符串列表转换为数字列表
【发布时间】:2020-11-16 23:02:45
【问题描述】:

我是 Prolog 的新手,想将字符串数字列表转换为数字列表。我会很感激解释,因为我正在努力使用这种语言进行列表操作。

这是我到目前为止所得到的(递归):

convert([], 0). # This is meant to be the simplest case, if there are no elements left in the list.
convert([H|T], L) :- # This is meant to be executed if there are elements in the list.
   string_to_atom(H, Elm), # Built in function from [here][1].
   convert([T|_],L1). # The recursive call to the tail T. Unsure about how to call this.

提前致谢!

编辑:链接到 string_to_atom 函数:https://www.swi-prolog.org/pldoc/man?predicate=string_to_atom/2

【问题讨论】:

  • 所以您想将 [''1'',''2'',''3''] 之类的内容转换为 [1,2,3] 对吗?
  • 没错!

标签: prolog


【解决方案1】:

您真的不需要手动进行递归。使用地图列表。 SWI-Prolog 中有number_string/2 可以双向工作。所以:

?- maplist(number_string, Numbers, ["1", "-2.0", "0.3e-2"]).
Numbers = [1, -2.0, 0.003].

解释是number_string/2 以两种方式工作:字符串到数字,或数字到字符串。请参阅文档。而 maplist 可以用来将谓词(如number_string/2)应用于列表,而无需自己进行递归。否则,你必须写:

numbers_strings([], []).
numbers_strings([N|Ns], [S|Ss]) :-
    number_string(N, S),
    numbers_string(Ns, Ss).

【讨论】:

    【解决方案2】:

    你就快到了!请注意,cmets 的字符是 %,而不是 #

    convert(Xs, Ys) 是建立Xs和Ys之间关系的谓词,这样当Xs中有元素时,头元素H就是与Elm的关系,其中string_to_atom(H, Elm)。所以 Elm 是 H 的原子等价物。

    convert([], []). % there are no elements in list Xs
    convert([H|Ts], [Elm|Es]) :- % This is meant to be executed if there are elements in the list.
       string_to_atom(H, Elm), % Built in function from [here][1].
       convert(Ts, Es). % The recursive call to the tail T
    

    您应该仔细阅读对 append/2 等标准谓词的解释。它们为您提供了与关系进行推理的正确方法。

    【讨论】:

    • append/2 不太标准。也许您的意思是 append/3 (带有三个参数)?
    • 在我年轻的时候理解 append/3 对我很有用!但是,没有 StackOverflow...
    • 现在我遇到了一个与引号有关的问题。我需要将单引号中的数字列表转换为数字列表,例如我需要将:['1','2','3'] 转换为输出:[1,2,3]。所有其他示例仅适用于双引号中的数字列表到数字列表,例如:["1","2","3"][1,2,3]
    • 我发现是atom_number/2 我需要从列表['1','2','3'] 转换为[1,2,3]
    【解决方案3】:

    这个例子有几个问题。我已经在下面发布了一个解决方案,可以做你想做的事。

    1. 在 SWI 序言中用 % 注释行。发布的代码无法与我的版本一起编译。
    2. L、L1 和 Elm 是 Singletons,通常指向错误。您将程序表示为逻辑表达式,解释器将无法假设它们之间有任何联系。在下面的解决方案中,我在结果项中将 L 和 Elm 组合成一个组合列表。
    3. H 始终是一个元素,而 T 是一个列表。因此 T 不能在 '|' 前面,但可以单独用作列表。
    4. convert 的“类型”在这两种情况下都不同,因为您在不同的情况下使用列表和数字。
        convert([ ], [ ]). 
        convert([H|T], [Elm|L]) :- string_to_atom(H, Elm), convert(T,L). 
        % call with
        % ?- convert(["a","b","c"],L).
        % L=[a, b, c].
    

    【讨论】:

      【解决方案4】:

      你可以试试:

      stringtonum(A,Y):-
          atom_number(A,K),
          number_codes(K,X1),
          maplist(plus(48),Y,X1).
      
      
      ?-stringtonum("1234",L)
      L = [1,2,3,4]
      
      ?-stringtonum("548765456",P).
      L = [5, 4, 8, 7, 6, 5, 4, 5, 6]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多