Hi,

You can also use "list comprehensions" with the string:

1
2
3
4
5
> [for i in "Hello" -> i];;
val it : char list = ['H'; 'e'; 'l'; 'l'; 'o']

> [for i in "Hello" -> String.make 1 i];;
val it : string list = ["H"; "e"; "l"; "l"; "o"]
By on 10/24/2007 4:43 AM ()

Thanks everyone...

I quite like this approach... Except I modded it to [for i in "Hello" -> String.of_char i]

not sure if there is any trade off compared to String.make 1 i

Thanks!

By on 10/24/2007 1:15 PM ()

You're right.

I'm used to the OCaml function String.make, but String.of_char is better (it's not available in OCaml).

By on 10/24/2007 1:52 PM ()

It's not as obvious as it first may seem, but the key is that string provides a ToCharArray method which returns an array of char. It's then fairly striaght forward to map these to strings and then turn them into a list.

1
2
3
4
5
let hello = "Hello"
let helloList = 
    hello.ToCharArray()
    |> Seq.map (fun c -> new string([|c|]))
    |> Seq.to_list

However all this conversion would add quite a bit of overhead, probably completly unnoticable in this trivial example, but well worth taking into account if you were going to do something that need to really preform. So in that case I'd recomend that you work directly with the characters returned by ToCharArray if possible.

By on 10/24/2007 4:22 AM ()

String's implement IEnumerable<char> so there isn't really a need to create a temporary array in you're example you could just do:

1
2
3
4
5
let hello = "Hello"
let helloList =
    hello
    |> Seq.map String.of_char
    |> Seq.to_list
By on 10/24/2007 7:29 AM ()

Hi,
You can use ToCharArray method and convert the returned array to F# list like this:

1
2
 
"hello".ToCharArray() |> Array.to_list
By on 10/24/2007 4:13 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper