Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer list to a string

Tags:

f#

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.

like image 511
user2898331 Avatar asked Nov 18 '25 06:11

user2898331


1 Answers

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) = ...
like image 114
Lee Avatar answered Nov 21 '25 08:11

Lee