Question

I am having some kind of homework and I am stuck to one point. I am given some facts like those:

word([h,e,l,lo]).
word([m,a,n]).
word([w,o,m,a,n]). etc

and I have to make a rule so that the user will input one list of letters and I should compare the list with the words I have and correct any possible mistakes. Here is the code I am using if the first letter is in the correct place:

mistake_letter([],[]).
mistake_letter([X|L1],[X|L2]):-
             word([X|_]),
             mistake_letter(L1,L2).

The problem is I don't know how to move to the next letter in the word fact. The next time the backtrack will run it will use the head of the word while I would like to use the second letter in the list. Any ideas on how to solve this?

I am sorry for any grammatical mistakes and I appreciate your help.

Was it helpful?

Solution

In order to move to the next letter in the word fact, you need to make the word from the fact a third argument, and take it along for the ride. In your mistake_letter/2, you will pick words one by one, and call mistake_letter/3, passing the word you picked along, like this:

mistake_letter(L1,L2):-
    word(W),
    mistake_letter(L1,L2,W).

The you'll need to change your base case to do something when the letters in the word being corrected run out before the letters of the word that you picked. What you do depends on your assignment: you could backtrack mistake_letter([],[],[])., declare a match mistake_letter([],[],_)., attach word's tail to the correction mistake_letter([],W,W). or do something else.

You also need an easy case to cover the situation when the first letter of the word being corrected matches the first letter of the word that you picked:

mistake_letter([X|L1],[X|L2],[X|WT]):-
    mistake_letter(L1, L2, WT).

Finally, you need the most important case: what to do when the initial letters do not match. This is probably the bulk of your assignment: the rest is just boilerplate recursion. In order to get it right, you may need to change mistake_letter/3 to mistake_letter/4 to be able to calculate the number of matches, and later compare it to the number of letters in the original word. This would let you drop "corrections" like [w,o,r,l,d] --> [h,e,l,l,o] as having only 20% of matching letters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top