2

I'm practicing F# programming for the first time and I was wondering if there was a command in the language that would emulate the equivalent of a Switch/Case command in C#? I want to make sure to optimize programs so that they don't have to be reset every time to try a different route of the program (e.g. Creating three kinds of area calculators and having to reset to try each one out.)

Edit: I completely forgot about showing the code as an example. This is what I want to try and edit.

```module AreaCalculator =
printfn "------------------------------"
printfn "Enter 1 to find a rectangle's area."
printfn "Enter 2 to find a circle's area."
printfn "Enter 3 to find a triangle's area."
printfn "Enter here: "
let stringInput = System.Console.ReadLine()

if stringInput = "1" then
  printfn "What is the rectangle's length: "
  let rlString = System.Console.ReadLine()
  printfn "What is the rectangle's width: "
  let rwString = System.Console.ReadLine()

  let rlInt = rlString |> int
  let rwInt = rwString |> int
  let rectArea = rlInt * rwInt

  printfn "The area of the rectangle is: %i" rectArea
elif stringInput = "2" then
  let PI = 3.14156
  printfn "What is the circle's radius: "
  let radiusString = System.Console.ReadLine()
  let radiusInt = radiusString |> float
  let cirlceArea = (radiusInt * radiusInt) * PI

  printfn "The area of the circle is : %f" cirlceArea


elif stringInput = "3" then
  printfn "What is the triangle's base: "
  let baseString = System.Console.ReadLine()
  printfn "What is the triangle's height: "
  let heightString = System.Console.ReadLine()
  
  let baseInt = baseString |> int
  let heightInt = heightString |> int
  let triArea = (heightInt * baseInt)/2

  printfn "The area of the triangle is: %i" triArea

else
  printfn "Please try again"

It works fine as is, but I'd like to see if I can rework the program so it doesn't have to be reset every time you want to calculate a different shape's area. I've tried making stringInput a mutable variable, as I had seen in a presentation, but it just results in an error like this:

/home/runner/F-Practice-1/main.fs(59,5): error FS0588: The block following this 'let' is unfinished. Every code block is an expression and must have a result. 'let' cannot be the final code element in a block. Consider giving this block an explicit result.

What can I do to remedy this?

Coji
  • 53
  • 5

1 Answers1

2

The equivalent construct in F# is called match:

let stringInput = System.Console.ReadLine()
match stringInput with
    | "1" ->
        printfn "What is the rectangle's length: "
        // ...
    | "2" ->
        printfn "What is the circle's radius: "
        // ...
    | "3" ->
        printfn "What is the triangle's base: "
        // ...
    | _ ->
        printfn "Please try again"

More details here.

Brian Berns
  • 15,499
  • 2
  • 30
  • 40