Home > Blockchain >  Recursively shorten a string in OCaml
Recursively shorten a string in OCaml

Time:10-27

Hey would anyone be able to help me create a function in OCaml that would take in a string and recursively return the string with less and letters. I am trying to use the sub string and recursion to accomplish this, any ideas that could point me in the right direction?

String
Strin
Stri
Str
St
S

I have used LISP and created a car and cdr function

let car = function
  | [] -> raise Not_found
  | first :: _ -> first
and cdr = function
  | [] -> raise Not_found
  | _ :: rest -> rest

CodePudding user response:

It's difficult to help because you don't describe clearly what you're trying to do. From your example it looks like you might want to just print out shorter and shorter strings. But that's not the same as "returning" the strings.

It seems to me it would make more sense to work directly with strings than to convert to lists of characters. You can use String.sub to make a new string that is a substring of another. So for example:

# let s = "example" in String.sub s 0 (String.length s - 1);;
- : string = "exampl"

If you want to return a list of shorter and shorter strings, you can write a recursive function. Your function would (in essence) add the full string to the head of the list created by calling itself recursively on a string that is one shorter.

I won't say any more, because figuring out how recursion works and appreciating its expressive power is one of the reasons that people study functional languages like OCaml.

I hope this is helpful

CodePudding user response:

You want to use the String.sub function as mentioned by Jeffrey.

If you want "String" to become:

String
Strin
Stri
Str
St
S

You need:

String.sub "String" 0 6
String.sub "String" 0 5
String.sub "String" 0 4
String.sub "String" 0 3
String.sub "String" 0 2
String.sub "String" 0 1

Only one argument changes: the length of the substring. If you want progressively shorter strings, you just need progressively shorter lengths.

Assuming you can generate those values recursively, you simply need:

let substrings s =
  let lengths = ... in
  lengths |> List.map (String.sub s 0)
  • Related