Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Iterate A String In F#?

Tags:

string

f#

I've got 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'm trying to convert a .Net string to a .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 don't specify the type of s, this is the type signature I see:

val toSecureString : char [] -> SecureString

But since I don't want to have to manually create an array of chars for the argument each time, it seems like I am missing something. How can I make this code work with a string parameter being passed in?

If it makes a difference I'm testing on F# 2.0 (Build 4.0.40219.1).

Any hints welcome. If this has already been asked and answered, post a link in the comments and I'll close this question.

like image 885
Onorio Catenacci Avatar asked Nov 29 '22 09:11

Onorio Catenacci


2 Answers

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

like image 118
kvb Avatar answered Dec 26 '22 11:12

kvb


To manipulate a string as a char seq, one can use String module. This works:

let toSecureString s =
    let sString = new SecureString()
    String.iter sString.AppendChar s
    sString
like image 45
pad Avatar answered Dec 26 '22 12:12

pad