Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Change List of Chars To String?

Tags:

In F# I want to transform a list of chars into a string. Consider the following code:

let lChars = ['a';'b';'c'] 

If I simply do lChars.ToString, I get "['a';'b';'c']". I'm trying to get "abc". I realize I could probably do a List.reduce to get the effect I'm looking for but it seems like there should be some primitive built into the library to do this.

To give a little context to this, I'm doing some manipulation on individual characters in a string and when I'm done, I want to display the resulting string.

I've tried googling this and no joy that way. Do I need to just bite the bullet and build a List.reduce expression to do this transformation or is there some more elegant way to do this?

like image 762
Onorio Catenacci Avatar asked Nov 19 '09 19:11

Onorio Catenacci


People also ask

How do I string a list of characters in Python?

To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.

Can you convert a char array to string?

Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied.

How do I convert a list to a string in one line?

To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.


2 Answers

Have you tried

System.String.Concat(Array.ofList(lChars)) 
like image 100
JaredPar Avatar answered Oct 10 '22 11:10

JaredPar


How many ways can you build a string in F#? Here's another handful:

let chars = ['H';'e';'l';'l';'o';',';' ';'w';'o';'r';'l';'d';'!']  //Using an array builder let hw1 = new string [|for c in chars -> c|]  //StringBuilder-Lisp-like approach open System.Text let hw2 =      string (List.fold (fun (sb:StringBuilder) (c:char) -> sb.Append(c))                        (new StringBuilder())                        chars)  //Continuation passing style let hw3 =     let rec aux L k =         match L with         | [] -> k ""         | h::t -> aux t (fun rest -> k (string h + rest) )     aux chars id 

Edit: timings may be interesting? I turned hw1..3 into functions and fed them a list of 500000 random characters:

  • hw1: 51ms
  • hw2: 16ms
  • hw3: er... long enough to grow a beard? I think it just ate all of my memory.
like image 25
cfern Avatar answered Oct 10 '22 12:10

cfern