I am trying to achieve the following. Input is list [8;9;4;5;7] and output should be "8,9,4,5,7," Note the "," in the output
I tried the following
let rec ConvertToString list =
match list with
| head :: tail -> head.ToString() + ConvertToString tail
| [] -> ""
let op= [8;9;4;5;7] |> ConvertToString
But the output which i get is val me : string = "89457"
Can anyone kindly suggest how to get get the "," in the output. The function should be generic.
You need to add the comma between the head and the converted tail, and need another case to convert the last element so you don't add a separating comma.
let rec ConvertToString list =
match list with
| [l] -> l.ToString()
| head :: tail -> head.ToString() + "," + ConvertToString tail
| [] -> ""
Note you can also define your function using String.concat:
let ConvertToString l = l |> List.map (fun i -> i.ToString()) |> String.concat ","
or String.Join:
let ConvertToString (l: 'a seq) = System.String.Join(",", l)
If you only want to allow ConvertToString to take int list arguments, you can specify the type of the input argument explicitly:
let ConvertToString (l : int list) = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With