Many files can be most effectively processed as byte
arrays—in F#, we can read byte
arrays and create them. The language even has special support for byte
arrays.
With the B suffix, on a string
literal, we can create a byte
array. This is the easiest way to initialize a small byte
array for use in an F# program.
This program uses byte
arrays in a variety of ways. Because it use a type from the System.IO
namespace, it has an "open System.IO
" directive at the top.
byte
array from the disk by calling File.ReadAllBytes
. The path will need to be adjusted to point to an existing file.byte
array literal. This syntax uses the uppercase "B" at the end of a string
literal.byte
array with byte
literals with the array initialization syntax.byte
array with a for-in
loop, printing them as we go along.Array.map
, we add 10 to each element of the array. Then we use Seq.iter
to print each value in the new array.open System.IO // Part 1: read in file from disk as byte array. let data = File.ReadAllBytes(@"/Users/sam/programs/output.webp") printfn $"Data length = {data.Length}" // Part 2: create a byte array with string syntax. let data2: byte[] = "cute dog"B printfn $"Data2 length = {data2.Length}" // Part 3: create a byte array with integer syntax. let data3 = [|100; 101; 102; 103|] printfn $"Data3 length = {data3.Length}" // Part 4: use separate lines for each value (indentation is important). let data4 = [|100 101 102 103|] printfn $"Data4 length = {data4.Length}" // Part 5: loop over elements in byte array. for b in data4 do printfn $"Byte in data4 = {b}" // Part 6: add to each element in byte array and print it out with Seq.iter. let result = Array.map (fun x -> x + 10) data4 result |> Seq.iter (fun x -> printfn $"Byte in result = {x}")Data length = 4796 Data2 length = 8 Data3 length = 4 Data4 length = 4 Byte in data4 = 100 Byte in data4 = 101 Byte in data4 = 102 Byte in data4 = 103 Byte in result = 110 Byte in result = 111 Byte in result = 112 Byte in result = 113
Byte arrays can be used throughout F# programs in the same way as other arrays. Functions like Array.map
can be used with byte
arrays.