F# CheatSheet
# Create new project
dotnet new console -n test1 -lang f#
Tweets
- Tipos no F#
- Is working with Excel files supposed to be this easy? #fsharp #dotnet
- DSL design comparation
- 3D vector operations
- Feliz - trick to import CSS into F# views
- Using ComputeSharp from F#
- Photino.NET is an Electron for .NET but smaller?
- Active patterns
- Decimal arithmetic
- AST for F#
- F# pipes
- OR patterns
- Use FelizEngine instead of Razor on AspNetCore.Mvc
- Recursive function calls
- Sutil with Tailwind CSS
- Match conditions in F# Obs.: Labels are wrong
- Bitcoin coding
- F# lambdas are awesome 1
- How to use F# to create shell scripts?
Samples
- crdt-examples - implementations of various CRDTs
Codes
// Functions
let linear x = 2.0 * x
let quadratic x = x ** 2
// read a line on console
open System
let line = Console.ReadLine()
printfn "Read line %s" line
// Defining a list
let lista = [
2
3 ]
// List just par numbers from a descrecent list
[9 .. -1 .. 1] |> List.filter (fun x -> x % 2 = 0)
// Calling an API using the F# Data Http utility:
// Source: https://stackoverflow.com/questions/62408621/f-with-http-fs-not-able-to-execute-graphql-apis
Http.RequestString
( "https://swapi.graph.cool",
httpMethod="POST", headers=[ HttpRequestHeaders.ContentType("application/json") ],
body=TextRequest("{\"query\": \"{ allFilms { title } }\"}")
printfn
// hello world
open System
[<EntryPoint>]
let main argv =
let square x = x * x
let squared = List.map square [1;2;3;5;7]
printfn "%A" squared
0 // return an integer exit code
Array.map (fun x -> -x) [|0..9|];;
// val it : int [] = [|0; -1; -2; -3; -4; -5; -6; -7; -8; -9|]
List.map (fun x -> -x) [0..9];;
// val it : int list = [0; -1; -2; -3; -4; -5; -6; -7; -8; -9]
Seq.map (fun x -> -x) { 0..9 };;
// val it : seq<int> = seq [0; -1; -2; -3; ...]
Format | Type |
---|---|
%s | string |
%i | integer |
%u | unsigned integer |
%f | float |
%b | boolean |
%O | other objects |
%o | octal |
%x | lowercase hex |
%X | uppercase hex |
%A | native F# types |
functions
open System
let ``print emoji ๐ฃ`` =
printfn "๐ฃ"
``print emoji ๐ฃ``
F# Types with .NET 5
Just as a quick update, various things do work.
This example now works in .NET 5:
open System
open System.Text.Json
[<EntryPoint>]
let main _argv =
let m1 = Map.empty<string, string> |> Map.add "answer" "42"
let json1 = JsonSerializer.Serialize(m1)
printfn "JSON1 %s" json1
let m2 = Map.empty<string, Version> |> Map.add "version" (Version("10.0.1.1"))
let json2 = JsonSerializer.Serialize(m2)
printfn "JSON2 %s" json2
0
F# records and anonymous records now appear to work (nested records example):
open System
open System.Text.Json
type Person = { Name: string; Age: int }
type Gaggle = { People: Person list; Name: string }
[<EntryPoint>]
let main _argv =
let r1 =
{
People =
[ { Name = "Phillip"; Age = Int32.MaxValue }
{ Name = "Ryan Nowak"; Age = Int32.MinValue } ]
Name = "Meme team"
}
let r2 =
{|
r1 with
FavoriteMusic = "Dan Roth's Banjo Bonanza"
|}
printfn $"{JsonSerializer.Serialize r1}"
printfn $"{JsonSerializer.Serialize r2}"
0
But DUs are still missing. FSharp.SystemTextJson is still the way to serialize F# union types.
C# Interop
// ResizeArray is the name of the #CSharp generic list class in #FSharp, so you can do:
let csList = ResizeArray [| rec01; rec02; rec03 |]
use
Using // Fonte: https://twitter.com/LucasTeles42/status/1317945856641978375
open System
let main =
use recurso = {
new IDisposable with
member this.Dispose() =
printfn "liberando recurso..."
}
printfn "acabou..."
Using Feliz
List Comprehension
// Source https://twitter.com/LucasTeles42/status/1335981686794936320
> let items x = [
- 1
- 2
- if x then 3
-
- let n = 10
- yield! [4..n]
-
- n + 1
-
- for numero = n + 2 to n * 2 do
- numero
- ];;
val items : x:bool -> int list
> printfn "%A" (items true);;
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20]
val it : unit = ()
Sync/Async
let work = async { do printfn "Hi" }
work
|> Async.RunSynchronously
FSI (F# Repl)
Started with:
dotnet fsi
Options:
#help
- Exibe informaรงรตes sobre as diretivas disponรญveis.#I
- Especifica um caminho de pesquisa de assembly entre aspas.#load
- Lรช um arquivo de origem, compila e o executa.#quit
- Finaliza uma sessรฃo do F# interativo.#r
- Faz referรชncia a um assembly.#time ["on"|"off"]
- Por si sรณ, #time alterna se deve exibir informaรงรตes sobre o desempenho. Quando habilitado, o F# interativo mede informaรงรตes em tempo real, em tempo de CPU e de coleta de lixo de cada seรงรฃo do cรณdigo que รฉ interpretado e executado.
References: