Recursive function to check if a char is a letter


I need to create a recursive functio> boo*l which returns true if the character string contains only letters (w

can someone please help me to do that?



  • make a function that checks if a single character is a letter (Char.code);
  • make a recursive function that checks if the first element of the string is a letter and calls itself on the substring taken from the second element on (String.sub).

Pattern matching is enough to test if a character is a letter. And recursively calling String.subis a bad idea. It is better to write a function that test that the n-th character is a letter, then write a recursive function that tests that every characters is a letter.

1 Like

let isn x ->

if int_of_c& int_of_char x <=

else if int_of_char xn true

else false;;

letfun s ->

let recn s ->

if is_letters) 1 1)

else false;;

how do i increment?

but can i have a recursive function a pattern matching?

You only need one recursive function , not two. And it is_letter that can be implemented with pattern matching.
You can put your code inside

your code
``` <

to make your code blocks more readable. To “increment”, you should transform your index into a function argument. For instance, you could write a function:

let rec only_letters_before pos s = ...

which is true if all characters before pos in s are letters.

i did that but it is not working i’m so bad

You are still using two recursive functions, this is one more than needed.
In particular, what is your function index returning?

but you told me to write a recurvise function for the index? :frowning:

You misread me: the index (aka the position in the string currently under examination) should be an argument of the main recursive function.

but i only have the String in argument? im so sorry

You can write an auxiliary recursive function that adds an integer argument (which is a more generic version) and then call it in your main function:

let rec only_letters_before pos s = ...
let check_letter s = only_letters_before (...) s

This is a classic scheme: the recursive function uses more argument because it keep tracks of some intermediary state.

1 Like

edit : aww its working!!! i love you i love you i love you! thank you! have a good day mate! thank you !

Since you’ve found a solution, I’ll provide my “bad idea” implementation for comparison. Keep in mind that octachrons’s remarks are totally right.

let is_alpha c =
  let i = Char.code c in
    if i >= 65 && i <= 90 || i >= 97 && i <= 122 then true
    else false

let rec letter s =
  let l = String.length s in
    if l = 0 then false
      if not (is_alpha s.[0]) then false
        if l = 1 then true
        else letter (String.sub s 1 (l-1))
1 Like

oh thank you! it will help me too! thank you for your help