how to print the first letter of few words in prolog list?

782 Views Asked by At

I want to print the name code input by user

begin:-read(X),
      name(X,L),
      write('Name Code: '),
      beginStr(L).

beginStr([H|T]):-
                 
                 put(H),
                 beginStr(T).

beginStr([]):-nl.

The Name Code below is the output i want to get, what else should be added to my code

| ?- begin.
|: 'Jenny Liz Ane'.
Name Code: JLA
yes


3

There are 3 best solutions below

2
Reema Q Khan On

1- First the user enters his/her first/middle/last name.

2- It is read.

3- string_chars breaks the string into characters : peter will become p,e,t,e,r

4- getFirstLetter Predicate extracts the first element from the list: from peter we get p.

5- upcase_atom convert lowercase letters to uppercase: p will become P.

6- display the answer using write.

 k:- 
  write('Enter First name: '),nl, 
  read(FName),nl, 
  string_chars(FName,N1),
  getFirstLetter(N1,L1),
  upcase_atom(L1,Str1),
  
    
  write('Enter Middle name: '),nl, 
  read(MName),nl, 
  string_chars(MName,N2),
  getFirstLetter(N2,L2),
  upcase_atom(L2,Str2),
  
    
  write('Enter Last name: '),nl, 
  read(LName),nl, 
  string_chars(LName,N3),
  getFirstLetter(N3,L3),
  upcase_atom(L3,Str3),
  write(Str1),write(' '),write(Str2),write(' '),write(Str3).  

 getFirstLetter([H|_],H).

Example:

?-k.

Enter First name:
peter

Enter Middle name:
jane

Enter Last name:
mary

P J M
5
Duda On

Ok, I have two different approaches therefore 2 answers.
First approach: print the first character and each character after a space:

beginStrSpace(Name):-
    string_chars(Name,[H|T]),
    write(H),
    spaces(T).

spaces([]):-
    nl.
spaces([' ',H|T]):-
    !,
    write(H),
    spaces(T).
spaces([_|T]):-
    spaces(T).

?- beginStrSpace("Hello there").
Ht
true.

The idea is to split the strings into a list of characters and print the first one. The character list will then be proceeded. If the current head of the list is a space (' ') then the following character is printed, the rest is proceeded. If the first character is not a space, the predicate just seaches in the rest list until eventually the list is empty.

0
Duda On

My second approach would to be to search for capital letter

capital(C):-
    member(C, ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']).
   
beginStrCapital(Name):-
    string_chars(Name,L),
    capitals(L).

capitals([]):-
    nl.
capitals([H|T]):-
    (    capital(H)
    ->   write(H)
    ;    true
    ),
    capitals(T).

?- beginStrCapital("Hello There.").
HT
true.

The idea is to go through the list of letters and oif a letter is a capital, print it. I could not find the Character-Number conversion on the fly so I just am asking if a char is a member of the list of capitals. This program will not detect non-capital letters as in "Ludwig van Beethoven".