Return vowels from word

2019-08-09 14:55发布

I've got this work to do and my teacher gave me a prolog file with the following facts:

vowel(a).
vowel(e).
vowel(i).
vowel(o).
vowel(u).

consonant(b).
consonant(c).
consonant(d).
consonant(f).
consonant(g).
consonant(h).
consonant(j).
consonant(k).
consonant(l).
consonant(m).
consonant(n).
consonant(p).
consonant(q).
consonant(r).
consonant(s).
consonant(t).
consonant(v).
consonant(w).
consonant(x).
consonant(y).
consonant(z).

And I need to create a rule that is able to return the vowels. How can I do that?

The output would be something like this:

blafoo([s,a,r,a], X).
X = [a].

I can't use any prolog predicate.

标签: prolog
3条回答
孤傲高冷的网名
2楼-- · 2019-08-09 15:49

If your Prolog implements it, I would go with standard ISO sub_atom/5

 ?- W = amazon, sub_atom(W, _,1,_, C).
W = amazon,
C = a ;
W = amazon,
C = m ;
...

then

blafoo(Word, Wovel) :- sub_atom(Word, _,1,_, Wovel), vowel(Wovel).

edit after comment

Prolog doesn't 'returns' things, but you could always use a more appropriate naming and implementation for the relation, for instance like

word_vowels(Word, Wovels) :-
  findall(Wovel, (sub_atom(Word, _,1,_, Wovel), vowel(Wovel)), Wovels).
查看更多
Summer. ? 凉城
3楼-- · 2019-08-09 15:57

If you are mentioning both vowel/1 and consonant/1, you might be expected to write a pure, monotonic version. After all, why do you mention consonant/1?

word_vowels([], []).
word_vowels([C|Xs], Vs) :-
   consonant(C),
   word_vowels(Xs, Vs).
word_vowels([V|Xs], [V|Vs]) :-
   vowel(V),
   word_vowels(Xs, Vs).

?- word_vowels([a,m,a,z,o,n],Vs).
Vs = [a,a,o] ;
false.

Alternatively using tfilter/3:

vowel_truth(C,true) :-
   vowel(C).
vowel_truth(V,false) :-
   consonant(V).

?- tfilter(vowel_truth,[a,m,a,z,o,n],Vs).
Vs = [a,a,o] ;
false.
查看更多
闹够了就滚
4楼-- · 2019-08-09 16:02

setof/3 could be a good choice here:

?- setof(X,(member(X,[a,m,a,z,o,n]),vowel(X)),L).
L = [a, o].
查看更多
登录 后发表回答