guillermop
guillermop

Reputation: 15

Turning 1's and 0's to a list of characters in Prolog

I have a homework assignment using prolog and I'm translating a set of 1's and 0's to a different set of characters. For example, here are my facts

analog([1], .). 
analog([1, 1, 1], -).
analog([0], "").
analog([0, 0, 0], ^).
analog([0, 0, 0, 0, 0, 0, 0], #).

An example input would be a list like

  [1,1,1,0,1,1,1,
  0,0,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,1,1,
  0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,
  1,1,1,0,1,0,1,1,1,0,1,0,0,0,1,1,1,0,1,1,1,
  0,1,1,1]

I have the following code :

signal_morse([], []). %base case 
signal_morse([A, B, C | Rest, R) :- 
  analog([A, B, C], H), 
  signal_morse(Rest, T), 
  append([H], T, R).

It only currently checks the first three elements in a list and I want to be able to check for 1 element if the first three don't match with any of the facts.

For example, say I have [1, 0, 0], since that doesn't match with any of my rules I want the program to check [1] instead and keep looking through the rest of the list.

So I wanted to know if there is any sort of pattern matching I can do so if the code analog([A, B, C], H) fails to find a match, the code would then try to match just the first character like analog([A], H).

Upvotes: 1

Views: 96

Answers (1)

Daniel Lyons
Daniel Lyons

Reputation: 22803

I realize this probably doesn't help you with your homework, but this is such a perfect problem for DCGs I can't help but show you what it would look like.

analog(.) --> [1].
analog(-) --> [1,1,1].
analog("") --> [0].
analog(^) --> [0,0,0].
analog(#) --> [0,0,0,0,0,0,0].

analogs([]) --> [].
analogs([A|As]) --> analog(A), analogs(As).

Usage:

?- phrase(analogs(X), [1,1,1,0,1,1,1, 0,0,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,1,1, 0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0, 1,1,1,0,1,0,1,1,1,0,1,0,0,0,1,1,1,0,1,1,1, 0,1,1,1]).
X = ['.', '.', '.', "", '.', '.', '.', "", ""|...] ;

Anyway, to answer your actual question, Prolog can figure out the lengths on its own with something like this:

signal_morse([], []).
signal_morse(Signals, [Code|RemainingMorseCodes]) :-
    append(Signal, RemainingSignals, Signals),
    analog(Signal, Code),
    signal_morse(RemainingSignals, RemainingMorseCodes).

Upvotes: 3

Related Questions