Byte array. 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.
Example. 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.
Part 1 We get a byte array from the disk by calling File.ReadAllBytes. The path will need to be adjusted to point to an existing file.
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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.