Hi
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?
thanks
Hi
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?
thanks
HINT:
Pattern matching is enough to test if a character is a letter. And recursively calling String.sub
is 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.
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
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?
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.
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))
oh thank you! it will help me too! thank you for your help