如何用下划线替换列表中的元音? [英] How do I replace vowels in a list with underscore?

查看:55
本文介绍了如何用下划线替换列表中的元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符列表(基本上是一个单词),我想用下划线 ['_'] 替换单词中的元音并返回一个新列表.例如:

I have a list of characters (basically a word) and I want to substitute the vowels in the word by underscore ['_'] and return a new list. eg:

?-sub([s,e,g,e,d],A).  
 A=[s,_,g,_,d]

我尝试以相反的顺序构建新列表,最后当它退出谓词时调用它拆除所有内容并声明它找到了没有输出字符串的目标!

My attempt built the new list in the reverse order then finally when it exited from the predicate call it dismantle everything and declare that it found the goal without the output string!

我使用的算法是:选择列表中的元素并检查它是否是元音,然后将 ['_'] 或元素本身附加到新列表中.

The algorithm I used is: pick element of a list and check whether it is a vowel or not and append the ['_'] or the element itself to the new list.

sub([],B).
sub([X|T1],Y):-
   ((vocal(X), append(['_'],Y,Z));
    (not(vocal(X)), append([X],Y,Z))),
    sub(T1,Z).

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

推荐答案

在 SWI-Prolog 中:

In SWI-Prolog:

sub(In, Out) :-
    maplist(vowel_to_underscore, In, Out).

vowel_to_underscore(Vowel, '_') :-
    vocal(Vowel),
    !.
vowel_to_underscore(X, X).

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

这篇关于如何用下划线替换列表中的元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆