Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generalise equations in Haskell?

Tags:

haskell

Apologies for my poor wording of the question. I've tried searching for an answer but not knowing what to search is making it very difficult to find one.

Here is a simple function which calculates the area of a triangle.

triangleArea        :: Float -> Float -> Float -> Float
triangleArea a b c 
    | (a + b) <= c  = error "Not a triangle!"
    | (a + c) <= b  = error "Not a triangle!"
    | (b + c) <= a  = error "Not a triangle!"
    | otherwise     = sqrt (s * (s - a) * (s - b) * (s - c))
        where s     = (a + b + c) / 2

Three lines of the function have been taken up for the purposes of error checking. I was wondering if these three lines could be condensed into one generic line.

I was wondering if something similar to the following would be possible

(arg1 + arg2) == arg3

where Haskell knows to check each possible combination of the three arguments.

like image 928
okeefj22 Avatar asked Nov 27 '25 14:11

okeefj22


1 Answers

I think @behzad.nouri's comment is the best. Sometimes doing a little math is the best way to program. Here's a somewhat overdone expansion on @melpomene's solution, which I thought would be fun to share. Let's write a function similar to permutations but that computes combinations:

import Control.Arrow (first, second)

-- choose n xs returns a list of tuples, the first component of each having
-- n elements and the second component having the rest, in all combinations
-- (ignoring order within the lists). N.B. this would be faster if implemented
-- using a DList.
choose :: Int -> [a] -> [([a],[a])]
choose 0 xs = [([], xs)]
choose _ [] = []
choose n (x:xs) =
  map (first (x:)) (choose (n-1) xs) ++
  map (second (x:)) (choose n xs)

So..

ghci> choose 2 [1,2,3]
[([1,2],[3]),([1,3],[2]),([2,3],[1])]

Now you can write

triangleArea a b c
  | or [ x + y <= z | ([x,y], [z]) <- choose 2 [a,b,c] ] = error ...
like image 62
luqui Avatar answered Nov 30 '25 05:11

luqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!