How to translate a string in F #?

I have the following F # code:

//Array iter version let toSecureString (s:string) = let sString = new SecureString() s |> Array.iter (fun cl -> sString.AppendChar cl) sString 

I am trying to convert .Net string to .Net SecureString. When I try to compile, I get a type mismatch error:

 stdin(60,10): error FS0001: Type mismatch. Expecting a string -> 'a but given a 'b [] -> unit The type 'string' does not match the type ''a []' 

If I do not specify type s, this is the type signature that I see:

 val toSecureString : char [] -> SecureString 

But since I don’t want to manually create an array of characters for the argument each time, it seems like I'm missing something. How can I get this code to work with the passed parameter of the string?

If that matters, I am testing F # 2.0 (Build 4.0.40219.1).

Any hints are welcome. If it has already been asked and answered, write a link in the comments, and I will close this question.

+4
source share
3 answers

Use Seq.iter , not Array.iter , because the strings are char seq , but not char[] s.

+12
source

To manipulate a string like char seq , you can use the String module . It works:

 let toSecureString s = let sString = new SecureString() String.iter sString.AppendChar s sString 
+5
source

You can also do this:

 SecureString(&&s.ToCharArray().[0], s.Length) 
+3
source

Source: https://habr.com/ru/post/1398638/


All Articles