Reputation: 109
I'm trying to convert a string into an list in f#, for my encryption algorithm. How would i solve this problem?
I know that (int char) returns the ascii value of the character, but i don't know how to map a whole string to an list of integers. As far as i know, there isn't a built in cast for string to list, or a mapping function that takes in a string and maps it to an list.
Upvotes: 3
Views: 396
Reputation: 66837
Strings are sequences of characters, so you can just map the conversion function over them:
"test" |> Seq.map int;;
val it : seq<int> = seq [116; 101; 115; 116]
If you really need an array and not a sequence you can tack another |> Seq.toArray
onto the end.
Upvotes: 2
Reputation: 3470
If what you are actually trying to do is to encrypt a unicode string, then you can use the .NET functions for converting the strings to and from byte arrays, whether UTF8 or UTF32. UTF8 is more memory efficient as bytes, but if you must store the chars as ints one to one, then going through UTF32 will result in less ints. Note that using ASCII encoding will not preserve unicode characters.
open System.Text
let s = "abc æøå ÆØÅ"
let asciiBytes = Encoding.ASCII.GetBytes s
let asciiString = Encoding.ASCII.GetString asciiBytes
printfn "%s" asciiString // outputs "abc ??? ???"
let utf8Bytes = Encoding.UTF8.GetBytes s
let utf8String = Encoding.UTF8.GetString utf8Bytes
printfn "%s" utf8String // outputs "abc æøå ÆØÅ"
let utf32Bytes = Encoding.UTF32.GetBytes s
let utf32String = Encoding.UTF32.GetString utf32Bytes
printfn "%s" utf32String // outputs "abc æøå ÆØÅ"
let bytesToInts (bytes: byte[]) = bytes |> Array.map (fun b -> int b)
let intsAsBytesToInts (bytes: byte[]) =
bytes |> Array.chunkBySize 4 |> Array.map (fun b4 -> BitConverter.ToInt32(b4,0))
let utf8Ints = bytesToInts utf8Bytes
printfn "%A" utf8Ints
// [|97; 98; 99; 32; 195; 166; 195; 184; 195; 165; 32; 195; 134; 195; 152; 195; 133|]
// Note: This reflects what the encoded UTF8 byte array looks like.
let utf32Ints = intsAsBytesToInts utf32Bytes
printfn "%A" utf32Ints
// [|97; 98; 99; 32; 230; 248; 229; 32; 198; 216; 197|]
// Note: This directly reflects the chars in the unicode string.
Upvotes: 1
Reputation: 817
let toAsciiVals (s:string) = Array.map int (s.ToCharArray())
Example in FSI:
> toAsciiVals "abcd";;
val it : int [] = [|97; 98; 99; 100|]
Upvotes: 3