Skip to content

Commit fc79f38

Browse files
authored
Merge pull request #962 from fsharp/dsyme/fixes
Tweak samples
2 parents ca23e7c + 0c6dfc1 commit fc79f38

10 files changed

+106
-96
lines changed

_snippets/aoc_day1.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
order: 16
2+
order: 20
33
title: AOC_Day1.fs
44
excerpt_separator: <!--more-->
55
code: |
@@ -22,7 +22,7 @@ code: |
2222
2323
"()(()((()((" |> parseChars |> findEndingFloor 0 |> printf
2424
---
25-
## Solve the Important Problems
25+
## Focus on the Challenges
2626

2727
F# excels at solving algorithmic challenges with clarity and precision. The code elegantly tracks an elevator's movement through a building by parsing directional instructions.
2828
<!--more-->
@@ -31,4 +31,4 @@ F# excels at solving algorithmic challenges with clarity and precision. The code
3131
- **Higher-order functions** like `fold` to accumulate state
3232
- **Function composition** with the pipeline operator for readable data flow
3333

34-
Notice how the solution reads almost like a plain English description of the problem, making it both maintainable and self-documenting.
34+
Solutions often read almost like a plain English description of the problem, making it both maintainable and self-documenting.

_snippets/async_expressions.md

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
order: 15
3+
title: AsyncExpressions.fs
4+
excerpt_separator: <!--more-->
5+
code: |
6+
// An async function
7+
let fetchDataAsync url = async {
8+
printfn "Fetching data from %s..." url
9+
do! Async.Sleep 1000 // Simulate network delay
10+
return sprintf "Data from %s" url
11+
}
12+
13+
// Using pattern matching in async code
14+
let processPersonAsync person = async {
15+
let result = validatePerson person.Age person.Name
16+
match result with
17+
| Ok validated ->
18+
return! fetchDataAsync $"profile/{validated.Name}"
19+
| Error msg ->
20+
return $"Validation error: {msg}"
21+
}
22+
23+
processPersonAsync { Name = "Snowdrop"; Age = 13}
24+
|> Async.RunSynchronously
25+
---
26+
## Async Programming made Easy
27+
28+
F# async expressions provide a powerful way to handle asynchronous programming, making it more readable and maintainable. They allow you to write non-blocking code that looks like synchronous code, which is particularly useful for I/O-bound operations.
29+
<!--more-->
30+
- **Async expressions** provide a clean syntax for defining asynchronous workflows
31+
- **Integration with existing libraries** makes it easy to use async expressions with other F# features
32+
- **Error handling** is simplified with the use of discriminated unions and pattern matching
33+
- **Seamless integration** with F#'s type system ensures type safety and reduces runtime errors
34+
- **Support for cancellation** and timeouts allows you to manage long-running operations effectively

_snippets/computation_expressions.md

+4-39
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,7 @@ order: 17
33
title: ComputationExpressions.fs
44
excerpt_separator: <!--more-->
55
code: |
6-
// Sequence generation
7-
let rec fizzBuzzSeq n =
8-
seq {
9-
yield
10-
match n with
11-
| x when x % 15 = 0 -> "fizzbuzz"
12-
| x when x % 3 = 0 -> "fizz"
13-
| x when x % 5 = 0 -> "buzz"
14-
| _ -> n.ToString()
15-
16-
yield! fizzBuzzSeq (n + 1)
17-
}
18-
19-
fizzBuzzSeq 1 |> Seq.take 100 |> Seq.iter (printfn "%s")
20-
21-
// Asynchronous programming with computation expressions
22-
let fetchDataAsync url = async {
23-
printfn "Fetching data from %s..." url
24-
do! Async.Sleep 1000 // Simulate network delay
25-
return sprintf "Data from %s" url
26-
}
27-
28-
// Custom computation expression for validation
6+
// Define a custom computation expression for validation
297
type ValidationBuilder() =
308
member _.Bind(x, f) =
319
match x with
@@ -38,7 +16,7 @@ code: |
3816
3917
type Person = { Name: string; Age: int }
4018
41-
// Using our custom computation expression
19+
// Use the custom computation expression
4220
let validatePerson age name = validate {
4321
let! validAge =
4422
if age >= 0 && age < 150 then Ok age
@@ -50,23 +28,10 @@ code: |
5028
5129
return { Name = validName; Age = validAge }
5230
}
53-
54-
// Using multiple computation expressions together
55-
let processPersonAsync person = async {
56-
let result = validatePerson person.Age person.Name
57-
match result with
58-
| Ok validated ->
59-
return! fetchDataAsync $"profile/{validated.Name}"
60-
| Error msg ->
61-
return $"Validation error: {msg}"
62-
}
63-
64-
processPersonAsync { Name = "Snowdrop"; Age = 13}
65-
|> Async.RunSynchronously
6631
---
67-
## Expressive Control Flow with Computation Expressions
32+
## Control the Complexity with Computation Expressions
6833

69-
F# computation expressions provide an elegant syntax for complex control flows with a clean, readable notation that some say is F#'s superpower.
34+
F# computation expressions give you an elegant syntax for compositional control flows with a clean, readable notation that some say is F#'s superpower.
7035
<!--more-->
7136
- **Simplified asynchronous code** makes non-blocking operations read like synchronous code
7237
- **Custom control flow abstractions** create domain-specific mini-languages

_snippets/domain_modelling.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
---
2-
order: 15
2+
order: 11
33
title: PaymentSystem.fs
44
code: |
55
type CardInfo = { Number: string; Expiry: string; Cvv: string }
6+
67
type BankInfo = { AccountNumber: string; RoutingNumber: string }
8+
79
type PayPalInfo = { Email: string; Token: string }
810
911
type PaymentMethod =
@@ -34,8 +36,8 @@ code: |
3436
payment.Amount
3537
pp.Email
3638
---
37-
## Making Invalid States Unrepresentable
38-
This example showcases F#'s ability to create precise domain models that prevent errors at compile time.
39+
## Domain Models made Simple and Safe
40+
F# gives you superb capabilities to create precise domain models that prevent errors at compile time.
3941

4042
- **Discriminated unions** model each payment method with exactly the fields it needs
4143
- **No "impossible" states** can exist - a credit card payment can't have a routing number

_snippets/fable.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ code: |
3030
]
3131
)
3232
---
33-
## F# for JavaScript Development
33+
## F# for JavaScript and the Full Stack
3434

35-
F# isn't just for .NET development - with [F# web technologies]({{ '/use/web-apps/' | relative_url }}), you can target JavaScript environments directly.
35+
F# is for both client and server. With [F# web technologies]({{ '/use/web-apps/' | relative_url }}), you can target JavaScript environments directly. This means you can use F# to build web applications, mobile apps, and even serverless functions that run in the cloud.
3636
<!--more-->
3737
- **Type-safe DOM manipulation** catches errors at compile time, not runtime
3838
- **Seamless React integration** with hooks and modern patterns

_snippets/helloworld.md

+5-8
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,20 @@ code: |
99
let greets = [
1010
"World"
1111
"Solar System"
12-
"Milky Way Galaxy"
13-
"Local Galactic Group"
14-
"Virgo Supercluster"
12+
"Galaxy"
1513
"Universe"
1614
"Omniverse"
1715
]
1816
1917
greets |> List.iter hello
2018
---
21-
## Concise and Expressive like Python
19+
## Concise like Python
2220

23-
This simple "Hello World" example demonstrates F#'s elegant syntax and functional approach to programming.
21+
F#'s elegant syntax and strong typing give you the tools to solve problems succinctly, robustly and happily.
2422
<!--more-->
25-
- **Concise function syntax** defines reusable functions with minimal boilerplate
26-
- **Clean list creation** uses indentation-based syntax without requiring commas
23+
- **Concise syntax** defines reusable functions with minimal boilerplate
24+
- **Simple lists** uses indentation-based syntax without requiring commas
2725
- **String interpolation** provides readable string formatting with the `$` prefix
2826
- **Pipeline operator** creates a readable left-to-right flow of data
29-
- **Higher-order functions** allow applying operations across collections easily
3027

3128
In just a few lines of code, F# provides a clean, readable implementation that would require significantly more boilerplate in many other languages. This expressive style becomes even more valuable as your programs grow in complexity.

_snippets/oop.md

+15-32
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
order: 11
2+
order: 10
33
title: OOP.fs
44
excerpt_separator: <!--more-->
55
code: |
@@ -10,52 +10,35 @@ code: |
1010
1111
// Class implementation with interface
1212
type Calculator(precision: int) =
13-
// Private field using let binding
14-
let mutable _precision = precision
1513
1614
// Interface implementation
1715
interface ICalculator with
18-
member this.Add x y = x + y
19-
member this.Multiply x y = x * y
16+
member _.Add x y = x + y
17+
member _.Multiply x y = x * y
2018
2119
// Public methods
22-
member this.Subtract(x, y) = x - y
23-
24-
// Property with explicit getter/setter
25-
member this.Precision
26-
with get() = _precision
27-
and set(value) = _precision <- value
20+
member _.Subtract(x, y) = x - y
2821
2922
// Method using property
30-
member this.RoundToPrecision(value: float) =
31-
System.Math.Round(value, this.Precision)
23+
member _.RoundToPrecision(value: float) =
24+
System.Math.Round(value, precision)
3225
3326
// Method with default parameter
34-
member this.Power(x: float, ?exponent: float) =
27+
member _.Power(x: float, ?exponent: float) =
3528
let exp = defaultArg exponent 2.0
3629
System.Math.Pow(x, exp)
3730
31+
// Object expression (anonymous implementation)
32+
let quickCalc =
33+
{ new ICalculator with
34+
member _.Add x y = x + y
35+
member _.Multiply x y = x * y }
36+
3837
// Type extension - add method to existing type
3938
type System.Int32 with
40-
member this.IsEven = this % 2 = 0
41-
42-
// Demo usage
43-
let demo() =
44-
// Object expression (anonymous implementation)
45-
let quickCalc =
46-
{ new ICalculator with
47-
member _.Add x y = x + y
48-
member _.Multiply x y = x * y }
49-
50-
// Class instantiation
51-
let calc = Calculator(2)
52-
53-
printfn "5 - 3 = %d" (calc.Subtract(5, 3))
54-
printfn "Is 10 even? %b" (10.IsEven)
55-
printfn "2.345 rounded = %f" (calc.RoundToPrecision(2.345))
56-
printfn "2^3 = %f" (calc.Power(2.0, 3.0))
39+
member x.IsEven = x % 2 = 0
5740
---
58-
## Object Programming Made Simple
41+
## Objects Made Simple
5942

6043
F# is **functional first** and **immutable by default**, but it also provides pragmatic support for object programming.
6144
<!--more-->

_snippets/sequence_expressions.md

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
order: 16
3+
title: SequenceExpressions.fs
4+
excerpt_separator: <!--more-->
5+
code: |
6+
// A function generating a sequence of numbers
7+
let rec fizzBuzzSeq n = seq {
8+
yield
9+
match n with
10+
| x when x % 15 = 0 -> "fizzbuzz"
11+
| x when x % 3 = 0 -> "fizz"
12+
| x when x % 5 = 0 -> "buzz"
13+
| _ -> n.ToString()
14+
15+
yield! fizzBuzzSeq (n + 1)
16+
}
17+
18+
// Process the sequence using a pipeline
19+
fizzBuzzSeq 1
20+
|> Seq.take 100
21+
|> Seq.iter (printfn "%s")
22+
---
23+
## Data Pipelines with Sequence Expressions
24+
25+
F# sequence expressions provide compositional, functional stream processing capabilities that integrate seamlessly with every part of the language.
26+
<!--more-->
27+
- **Simplified data generation** through sequence expressions
28+
- **Compositional data processing** through library routines
29+
- **On-demand evaluation** of data streams
30+
- **Fluent, maintainable code** that is easy to read and understand

_snippets/typeproviders.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ code: |
88
type PeopleDB = CsvProvider<"people.csv">
99
1010
let printPeople () =
11-
let people = PeopleDB.Load("people.csv") // this can be a URL
11+
let people = PeopleDB.Load("people.csv")
1212
1313
for person in people.Rows do
14-
// access the csv fields with intellisense and type safety!
14+
// Access the CSV fields with intellisense and type safety!
1515
printfn $"Name: %s{person.Name}, Id: %i{person.Id}"
1616
---
17-
## Type-Safe Access to External Data
17+
## Type-Safe, Integrated Data
1818

19-
F# Type Providers create a seamless bridge between your code and external data sources.
19+
F# Type Providers create a seamless bridge between your code and data sources.
2020
<!--more-->
2121
- **Zero-friction data access** connects to CSV, JSON, XML, SQL, and more without manual mapping
2222
- **Static typing at compile time** prevents runtime errors when accessing external data

_snippets/unitsOfMeasure.md

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
---
2-
order: 1
2+
order: 22
33
title: UnitsOfMeasure.fs
44
excerpt_separator: <!--more-->
55
code: |
6-
[<Measure>] type m // Meters
7-
[<Measure>] type s // Seconds
6+
open FSharp.Data.UnitSystems.SI
87
98
// Acceleration due to gravity
109
let g = 9.81<m/s^2>
@@ -17,9 +16,9 @@ code: |
1716
let fallDistance = distance fallDuration
1817
printfn $"Distance fallen in {fallDuration}s is {fallDistance}m"
1918
---
20-
## Units of Measure
19+
## Numaric Safety through Units of Measure
2120

22-
F# offers compile-time unit safety without runtime overhead, enforcing correctness mathematically.
21+
F# offers world-class compile-time unit safety without runtime overhead, giving you the power to express your domain in a type-safe way. This is particularly useful in scientific, engineering and financial applications where unit errors can lead to catastrophic results.
2322
<!--more-->
2423
- **Compile-time dimensional safety** catches errors before running, preventing scientific and engineering mistakes
2524
- **Domain-specific units** express quantities that directly reflect your problem space

0 commit comments

Comments
 (0)