how to pass a list in a predicate in prolog

前端 未结 2 601
眼角桃花
眼角桃花 2021-01-23 11:03

I want to store a paragram as a list in a variable and then call that list for counting how many times a particular word appears in that paragraph.

However, when I do th

相关标签:
2条回答
  • 2021-01-23 11:43

    The line in a prolog file:

    L = [hello,hello,hello].
    

    Means to prolog:

    =(L, [hello,hello,hello]).
    

    Which means you're attempting to define a predicate, =/2. So not only will you get a singleton warning about L (since L isn't used anywhere else in this predicate definition), but you'll also see an error about an attempt to re-define the built-in =/2 since prolog already has it defined.

    What you can do instead is:

    my_list([hello,hello,hello]).
    

    Then later on, you can do:

    my_list(L), counthowmany(hello,L,N).
    

    Note that this case works:

    L = [hello,hello,hello], counthowmany(hello,L,N).
    

    It works because it's not attempting to re-define =/2. It is just using the existing built-in predicate =/2.

    0 讨论(0)
  • 2021-01-23 11:50

    You do

    ?- X = [hello,how,are,you,hello,hello], counthowmany(hello, X, N).
    X = [hello, how, are, you, hello, hello],
    N = 3.
    

    First you first bind X ans then you ask for this specific X.

    Example 2.

    ?- counthowmany(hello, X, N).
    X = [],
    N = 0.
    
    0 讨论(0)
提交回复
热议问题