Kai
Kai

Reputation: 2013

Using F# to calculate triangle

I'm trying to write a program to calculate triangles. Can anyone give me a short code in F# sharp for this calculation?

enter image description here

This is what I have so far, but I'm not convinced it's the best way:

let area a b c = 
  let s = sqrt((a + b + c) / 2) 
  sqrt(s * (s - a) * (s - b) * (s - c))

Upvotes: 1

Views: 521

Answers (2)

Paolo Falabella
Paolo Falabella

Reputation: 25844

It seems you're trying to apply different formulas depending on the type of triangle you have. If you have three sides you use Heron's formula, if you have one side you're assuming the triangle is equilateral, if you have two sides you're assuming the triangle is right and the two sides are the catheti. If I interpreted correctly, I would define a discriminated union, like this:

type Triangle =
| Generic of float * float * float
| Equilateral of float
| Right of float * float

let area (t : Triangle) : float = 
  match t with 
  | Generic (a, b, c) -> let s = (a + b + c) / 2. 
                         sqrt(s*(s-a)*(s-b)*(s-c))
  | Equilateral a     -> sqrt(3.) * (a ** 2.) / 4.
  | Right (a, b)      -> (a * b) / 2.

// testing
let triangles = [Generic (2., 3., 4.); Equilateral 2.; Right (2., 3.)] 

triangles |>
List.iter (fun t -> Console.WriteLine(area t))

Upvotes: 5

Gus
Gus

Reputation: 26174

Just the translation of those formulas? Should be something like this:

let area  a = (a **  2. / 4.) * sqrt 3.

let area' a b = a * b / 2.

let area'' a b c = 
    let s = (a + b + c) / 2.
    sqrt(s * (s - a) * (s - b) * (s - c))

Upvotes: 3

Related Questions