Doplnenie. Drvivá väčšina funkcií sa nachádza v module List.
https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-listmodule.html.
Napr. funkcie pre sortovanie:
let nums = [ -1; 6; -2; 3; 0; -4; 5; 1; 2 ] nums |> List.sort |> printfn "%A" nums |> List.sortDescending |> printfn "%A" nums |> List.sortBy (abs) |> printfn "%A" nums |> List.sortByDescending (abs) |> printfn "%A"
Na inicializáciu môžeme napríklad použiť List.init.
List.init 5 (fun e -> e * e)
F# má naozaj bohatú syntax na definovanie zoznamov pomocou list comprehensions. Základom sú range a generátory. Môžeme použiť viaceré podmienky a for cykly.
let vals = [ -1; 0; 2; -2; 1; 3; 4; -6 ]
let pos =
[ for e in vals do
if e > 0 then yield e ]
printfn "%A" pos
printfn "---------------------------------"
[ for e in 1 .. 100 -> e * e ] |> printfn "%A"
printfn "---------------------------------"
[ for a in 1 .. 100 do
if a % 3 = 0 && a % 5 = 0 then yield a] |> printfn "%A"
printfn "---------------------------------"
let vals3 =
[ for x in 1 .. 3 do
for y in 1 .. 10 -> x, y ]
printfn "%A" vals3
Zvláda to aj vnorené let výrazy.
let vals = [ 1; -2; -3; 4; 5 ]
[ for v in vals do
let f = fun e -> e > 0
if f(v) then yield v ] |> printfn "%A"
Dokonca tam môžeme vnoriť aj match pattern.
let res =
[ for e in 1..100 do
match e with
| e when e % 3 = 0 -> yield "fizz"
| e when e % 5 = 0 -> yield "buzz"
| e when e % 15 = 0 -> yield "fizzbuzz"
| _ -> yield (string e) ]
printfn "%A" res26. 9. 2023, 13:15 editováno autorem komentáře