How do I convert a list of chars into a list of strings in F#?

63 Views Asked by At

I have a list of chars that looks like this ['a'; 'b'; '&'; 'c']. I now want to convert this into a list of strings ["a"; "b"; "&"; "c"] and not one string "ab&c" since in the end, I want to compare two lists with strings. How do I go from a list of characters to a list of strings? Thanks a lot for the help

let varL1 = ['a';'b';'&';'c']

let rec ConvertToString list =
   match list with
   | [l] -> l.ToString()
   | head :: tail -> head.ToString() + "," + ConvertToString tail
   | [] -> ""

ConvertToString varL1

I tried the code abovce but his gives me "ab&c" which is not what I am looking for. I am looking for ["a";"b";"&";"c"]

2

There are 2 best solutions below

1
deviep11 On BEST ANSWER
let varL1 = ['a'; 'b'; '&'; 'c']

let rec ConvertToString list =
    match list with
    | head :: tail -> string head :: ConvertToString tail
    | [] -> []

let varL2 = ConvertToString varL1

Try this.

0
smoothdeveloper On

When you want to transform a list of 'a into a list of 'b, the List.map function is the most straight forward:

let listOfChars = ['a';'b';'&';'c']
let listOfStrings = 
  listOfChars 
  |> List.map string

The List.map function expects a function from 'a to 'b ('a -> 'b), and a list of 'a, and returns list of 'b: full signature being ('a -> 'b) -> 'a list -> 'b list.

In the code above, I pass the string function, which converts the input (a char in this particular case) to a string.

https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-listmodule.html#map https://fsharp.github.io/fsharp-core-docs/reference/fsharp-core-operators.html#string

Related Questions in F#

Related Questions in F#-INTERACTIVE