5
$\begingroup$

I am trying to write a function that takes English text and produces the corresponding Morse code. I have a function which works fine when the text consists of lower case letters. But I could not write a proper function which produces the corresponding Morse code when the text has capital letters.

ToMorseCode[text_String] := StringJoin[Map[Replace[{"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" -> "--.. ", " " -> "/ "}], Characters[text]]]
$\endgroup$
  • 2
    $\begingroup$ Btw., have you seen this? $\endgroup$ – Henrik Schumacher Mar 25 '18 at 17:58
  • $\begingroup$ For a long list of rules like yours, you might consider using Dispatch[] or Association[]. $\endgroup$ – J. M. is away Mar 25 '18 at 18:14
  • $\begingroup$ @Henrik, yes, that helped me to write my function, but I could not handle writing it with Association[] in a shorter way that will produce Morse code even though the text has capital letters. $\endgroup$ – Ilker Mar 25 '18 at 18:35
  • $\begingroup$ is there a way to make such a program trough the list function, how would that look? $\endgroup$ – Vince Mar 27 '18 at 15:31
  • $\begingroup$ Wolfram Challenge. $\endgroup$ – J. M. is away Oct 13 '18 at 6:35
12
$\begingroup$

I'm somewhat puzzled that OP hasn't written the, to my mind, rather simpler:

ToMorseCode[text_String] := StringReplace[
  ToLowerCase[text], {"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" -> "--.. ", " " -> "/ "}]
$\endgroup$
7
$\begingroup$

Use ToLowerCase[string] before applying your function.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.