Search code examples
listocamlmorse-code

Split a string into list of words' characters in Ocaml


So, I have homework and I'm doing my best to solve it. We have to translate from English to Morse code. Every word has to be separated.

Example: if I enter this is it should write: ["_";"....";"..";"..."]["..";"...."]

I wrote 2 functions so far (lowercase to uppercase and matching letters and numbers with Morse code) and now I need to write function which converts string to a list of list of characters like this:

stringSAllCaps "   ban an  a  ";;
- : char list list = [['B'; 'A'; 'N']; ['A'; 'N']; ['A']]
stringSAllCaps "banana";;
- : char list list = [['B'; 'A'; 'N'; 'A'; 'N'; 'A']]

I know how to convert a string into a list of characters, but have no idea what to do next. I don't need someone to solve that for me completely, just to guide me in right direction.

This is what I have done:

let explode niz =
  let rec exp a b =
    if a < 0 then b 
    else exp (a - 1) (niz.[a] :: b) in
  exp (String.length niz - 1) []
     ;;

edit:

ty for your help :) I've managed to solve this problem, but not like this. I will post it later. as I solved it and continued with my homework I realized that I had to use while and pointers and now I'm stuck again (pointers are not my best friends.. ). Any suggestions?

my solution at the moment:

# let explode str =
let rec exp = function
| a, b when a < 0 -> b
| a, b -> exp (a-1, str.[a]::b)
in
exp ((String.length str)-1, []);;
# let split lst ch =
let rec split = function
| [], ch, cacc', aacc' -> cacc'::aacc'
| c::lst, ch, cacc', aacc' when c = ch -> split (lst, ch, [], cacc'::aacc')
| c::lst, ch, cacc', aacc' -> split (lst, ch, c::cacc', aacc')
in
split (lst, ch, [], []);;

Solution

  • I guess you should start by:

    • Renaming the arguments of your recursive function to have a more explicit meaning (as index and current_word for instance)
    • Adding a new parameter in you recursive function to store the words already seen (seen_words)
    • testing whether niz.[a] is a blank char and do the right things if it is the case ie. update the current word or the already seen list of words.