Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

F# Practice Exercises

Twenty F# exercises with hidden solutions covering records, unions, pattern matching, options, results, collections, active patterns and async, plus a self-assessment checklist and what to learn next.

Reading F# teaches you to recognise it; writing it teaches you to think in it. This lesson is a workout: twenty exercises grouped by topic, with the solution to each tucked under a collapsible heading so you can try first. Write your answers in a script file and run them with dotnet fsi, or in an online F# playground; F# does not run in this site's editor, so the solutions are read-only code. A runnable C# check for one exercise is included at the end.

How to practise: try for at least ten minutes before you peek. Then compare. If your version differs, ask whether yours is shorter, safer or clearer, not just whether it passes.

Part 1: types and records

1. Temperature. Declare a record Reading = { City: string; Celsius: float } and write warmest : Reading list -> Reading option.

Solution
FSHARP
type Reading = { City: string; Celsius: float }

let warmest readings =
    match readings with
    | [] -> None
    | _ -> Some (List.maxBy (fun r -> r.Celsius) readings)

2. Shapes. Make a union Shape with Circle, Square and Triangle (base, height) and a function area.

Solution
FSHARP
type Shape =
    | Circle of radius: float
    | Square of side: float
    | Triangle of baseLength: float * height: float

let area = function
    | Circle r -> System.Math.PI * r * r
    | Square s -> s * s
    | Triangle (b, h) -> 0.5 * b * h

3. Typed ids. Create UserId and ProductId wrappers so getUser (ProductId 3) does not compile.

Solution
FSHARP
type UserId = UserId of int
type ProductId = ProductId of int

let getUser (UserId id) = $"user {id}"

4. Copy and update. Given { Name: string; Tags: string list }, write addTag tag item returning a new item with the tag added once (no duplicates).

Solution
FSHARP
type Item = { Name: string; Tags: string list }

let addTag tag item =
    if List.contains tag item.Tags then item
    else { item with Tags = item.Tags @ [ tag ] }

Part 2: pattern matching

5. FizzBuzz with a tuple pattern on n % 3, n % 5.

Solution
FSHARP
let fizzBuzz n =
    match n % 3, n % 5 with
    | 0, 0 -> "FizzBuzz"
    | 0, _ -> "Fizz"
    | _, 0 -> "Buzz"
    | _ -> string n

[ 1 .. 15 ] |> List.map fizzBuzz

6. List patterns. Write lastTwo that returns the last two elements of a list as an option of a tuple.

Solution
FSHARP
let rec lastTwo list =
    match list with
    | [ a; b ] -> Some (a, b)
    | _ :: rest -> lastTwo rest
    | [] -> None

7. Run-length encoding. Turn "aaabccdd" into [('a',3); ('b',1); ('c',2); ('d',2)].

Solution
FSHARP
let encode (s: string) =
    s
    |> Seq.toList
    |> List.fold (fun acc c ->
        match acc with
        | (x, n) :: rest when x = c -> (x, n + 1) :: rest
        | _ -> (c, 1) :: acc) []
    |> List.rev

8. Active pattern. Define a partial active pattern Email that matches strings containing exactly one @ and returns the user and domain.

Solution
FSHARP
let (|Email|_|) (s: string) =
    match s.Split '@' with
    | [| user; domain |] when user <> "" && domain <> "" -> Some (user, domain)
    | _ -> None

match "[email protected]" with
| Email (u, d) -> $"{u} at {d}"
| _ -> "not an email"

Part 3: options and results

9. Write tryParseInt : string -> int option, then sumValid : string list -> int that adds every parsable string.

Solution
FSHARP
let tryParseInt (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

let sumValid inputs = inputs |> List.choose tryParseInt |> List.sum

10. Write safeDivide returning Result<int, string> and average : int list -> Result<int, string> using it.

Solution
FSHARP
let safeDivide a b = if b = 0 then Error "divide by zero" else Ok (a / b)

let average xs = safeDivide (List.sum xs) (List.length xs)

11. Validate a registration: name not empty, age 18 to 120. Return Result<User, string list> collecting both errors if both fail.

Solution
FSHARP
type User = { Name: string; Age: int }

let validate name age =
    let errors =
        [ if System.String.IsNullOrWhiteSpace name then "name required"
          if age < 18 || age > 120 then "age must be 18-120" ]
    if errors.IsEmpty then Ok { Name = name; Age = age } else Error errors

12. Chain tryParseInt and a lookup Map<int, string> with Option.bind.

Solution
FSHARP
let names = Map [ 1, "Ada"; 2, "Grace" ]

let lookup text = tryParseInt text |> Option.bind (fun id -> Map.tryFind id names)

Part 4: collections and pipelines

13. From a list of words, return the ones longer than 3 characters, upper-cased and sorted.

Solution
FSHARP
let process words =
    words
    |> List.filter (fun w -> w.Length > 3)
    |> List.map (fun w -> w.ToUpper())
    |> List.sort

14. Group names by first letter into a Map<char, string list>.

Solution
FSHARP
let byInitial names =
    names
    |> List.groupBy (fun (n: string) -> n.[0])
    |> Map.ofList

15. Compute the first 10 Fibonacci numbers with Seq.unfold.

Solution
FSHARP
let fibs =
    Seq.unfold (fun (a, b) -> Some (a, (b, a + b))) (0, 1)
    |> Seq.take 10
    |> Seq.toList
// [0; 1; 1; 2; 3; 5; 8; 13; 21; 34]

16. Write pairs : 'a list -> ('a * 'a) list that pairs neighbours: [1;2;3] gives [(1,2);(2,3)].

Solution
FSHARP
let pairs list = list |> List.pairwise

Part 5: async and agents

17. Run three async tasks that each sleep 200 ms and return their index; collect the results in order.

Solution
FSHARP
let work i = async { do! Async.Sleep 200; return i }

[ 1; 2; 3 ] |> List.map work |> Async.Parallel |> Async.RunSynchronously
// [|1; 2; 3|] in about 200 ms

18. Write a MailboxProcessor that sums numbers posted to it and replies with the total on request.

Solution
FSHARP
type Msg =
    | Add of int
    | Total of AsyncReplyChannel<int>

let summer =
    MailboxProcessor.Start(fun inbox ->
        let rec loop sum =
            async {
                match! inbox.Receive() with
                | Add n -> return! loop (sum + n)
                | Total reply ->
                    reply.Reply sum
                    return! loop sum
            }
        loop 0)

19. Wrap async code so that an exception becomes Result<'T, string>.

Solution
FSHARP
let attempt work =
    async {
        match! Async.Catch work with
        | Choice1Of2 v -> return Ok v
        | Choice2Of2 ex -> return Error ex.Message
    }

20. Challenge: write a function evalRpn : string -> Result<float, string> for reverse Polish notation like "3 4 + 2 *" (14) using a stack as a list.

Solution
FSHARP
let evalRpn (input: string) =
    let step (stack: Result<float list, string>) (token: string) =
        stack
        |> Result.bind (fun s ->
            match token, s with
            | "+", b :: a :: rest -> Ok (a + b :: rest)
            | "-", b :: a :: rest -> Ok (a - b :: rest)
            | "*", b :: a :: rest -> Ok (a * b :: rest)
            | "/", b :: a :: rest when b <> 0.0 -> Ok (a / b :: rest)
            | "/", _ :: _ :: _ -> Error "division by zero"
            | ("+" | "-" | "*" | "/"), _ -> Error "not enough operands"
            | num, _ ->
                match System.Double.TryParse num with
                | true, n -> Ok (n :: s)
                | _ -> Error $"bad token '{num}'")
    input.Split ' '
    |> Array.fold step (Ok [])
    |> Result.bind (function
        | [ v ] -> Ok v
        | _ -> Error "malformed expression")
C# C# check for exercise 20 (RPN)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Self-assessment

flowchart LR
    A["1-4<br/>types"] --> B["5-8<br/>patterns"]
    B --> C["9-12<br/>option, result"]
    C --> D["13-16<br/>collections"]
    D --> E["17-20<br/>async, agents"]

Work through the parts in order; each builds on the previous one.

Tick yourself off honestly:

  • I can declare a record and a union and say when to use each.
  • I can write a function over a union and explain why the compiler warns about a missing case.
  • I know Option.map, bind and defaultValue and when to pick Result instead.
  • I can build a pipeline with List/Seq functions without writing a loop.
  • I can run work in parallel with Async.Parallel and explain why an agent needs no lock.

Where to go next

  • Re-read the Discriminated Unions and Result lessons, then redo the bank account project with a transfer command.
  • Build a small web API with Giraffe or Falco, or a data script that reads CSV with a type provider.
  • Compare with a sibling language track: C#, which shares the whole runtime and libraries.
  • Read other people's F#: the compiler repository's samples and open-source libraries such as FsToolkit and Fantomas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function keeps only the Some results of mapping a list with an option-returning function?

    List.choose maps and drops None in one step (exercise 9).
  2. 2. How do you run asyncs concurrently and get results in order?

    Async.Parallel returns an array in the original order (exercise 17).
  3. 3. Which function pairs each list element with its successor?

    List.pairwise turns [1;2;3] into [(1,2);(2,3)].
  4. 4. Why do the exercises recommend trying before reading the solution?

    Active recall beats passive reading.

Summary

  • Twenty exercises covered types, patterns, options and results, collections and async.
  • Prefer choose, bind, fold and pipelines over loops and mutation.
  • Make illegal states unrepresentable and error cases visible in types.
  • Keep practising on projects: events and agents, interpreters and text tools.

Next: F# Tutorial Home