Initialize list from string?

3636 views f#

I have the string "H1E1T1H1" for which I want to replace each '1' with a string such as "OP" and I think that this would be easiest accomplished using lists because of the ease of adding elements. However, I wonder how I can initialize a list from a sting? (if using lists actually does not make it much easier, please correct me :) )

answered question

1 Answer


The easiest way (and it is idiomatic in F#) is to use String.Replace method as follow:

let str = "H1E1T1H1"
let result = str.Replace("1","OP")

But in case you want FP just because you can... :)

|> (function | '1' -> "OP" | x -> string x)
|> String.concat ""

I case you wanted to replace the same character with different strings according to the character's index

|> Seq.mapi (fun i x ->
    match i,x with
    | (i, '1') when i < 4 || i > 6 -> "OP"
    | (_, x) -> string x)
|> String.concat ""

posted this

Have an answer?


Please login first before posting an answer.