# Recursive function to check if a char is a letter

Hi

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

thanks

HINT:

• 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

```ocaml
``` <

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?

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
else
if not (is_alpha s.[0]) then false
else
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