user2898331
user2898331

Reputation: 43

Convert integer list to a string

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.

Upvotes: 3

Views: 4426

Answers (3)

Lars
Lars

Reputation: 466

I think this is a nice version for integer lists:

let convertToString = List.map (sprintf "%i") >> String.concat ","

or if you want a generic version:

let convertToString l = l |> List.map (sprintf "%A") |> String.concat ","

Upvotes: 4

Rusty
Rusty

Reputation: 914

Just another way to do this:

let ConvertToString (l: int list) =
match l with
| [] -> ""
| h :: t -> List.fold (fun acc x -> acc + "," + x.ToString()) (h.ToString()) t

Upvotes: 0

Lee
Lee

Reputation: 144126

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) = ...

Upvotes: 7

Related Questions