chessguy
chessguy

Reputation: 165

Return a string instead of unit

I have a class method

  method return__string_sCorona =

    let est_vide chaine_de_car = List.exists ((=) "") strg in 
    let print_data name value = match nom  with 
      | [] -> ()
      | _ -> if not (is_empty name) then print_string value else () in

    begin
      print_data [self#get_province_state("Province or state: " ^ self#get_province_state ^ "\n");
      print_data [self#get_country_region] ("Country or region: " ^ self#get_country_region ^ "\n");
      print_data [self#get_last_update] ("Last Update: " ^ self#get_last_update ^ "\n");
      print_string("Lat et Long: " ^ string_of_float self#get_lat ^ " " ^ string_of_float self#get_long ^ "\n");
      print_string("Confirmed cases: " ^ string_of_int self#get_confirmed_cases ^ "\n");
      print_string("Death cases: " ^ string_of_int self#get_death_cases ^ "\n");
      print_string("Reestablished cases : " ^ string_of_int self#get_reestablished_cases ^ "\n");
      print_string("Active cases: " ^ string_of_int self#get_active_cases ^ "\n\n");
    end

which will print different information about Covid-19.

Actually, that method has type unit, but for some reasons, I need it return a string.

Instead of doing just calling my_object#return_string_sCorona, how can I return the string and print the result with print_string (my_object#return_string_sCorona)? It is important because I have to use it inside an interface using labltk.

Upvotes: 1

Views: 219

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

Add this to the beginning of the method

let buf = Buffer.create 512 in
. . .

Change all calls print_string s to Buffer.add_string buf s.

The end of the method would look like this:

. . .
Buffer.add_string buf 
      ("Active cases: " ^ string_of_int self#get_active_cases ^ "\n\n");
Buffer.contents buf
end

Update

Here's an example function that uses a buffer to accumulate a result. You should be able to rewrite your method in this style without too much trouble.

let show_intset x =
    let buf = Buffer.create 128 in
    let rec loop x n =
        if x <> 0 then
            begin
            if x mod 2 = 1 then
                begin
                if Buffer.contents buf <> "" then
                    Buffer.add_string buf ", ";
                Buffer.add_string buf (string_of_int n)
                end;
            loop (x / 2) (n + 1)
            end
    in
    loop x 0;
    Buffer.contents buf

Here's how it looks when you run the function in the toplevel:

# #use "p.ml";;
val show_intset : int -> string = <fun>
# show_intset 12;;
- : string = "2, 3"
# show_intset 1023;;
- : string = "0, 1, 2, 3, 4, 5, 6, 7, 8, 9"
# show_intset 1024;;
- : string = "10"

I hope this is helpful.

Upvotes: 2

Related Questions