2
\$\begingroup\$

I wrote some math formulas in Haskell and was wondering about how to clean the code up and make it more readable.

import Math.Gamma
pdf :: Double -> Double -> Double -> Double -> Double
pdf mu alpha beta x =
 ( beta / (2 * alpha * gamma ( 1/beta) ) ) **
 exp ( -1* ( abs(x - mu )/alpha )) ** beta
cdf :: Double -> Double -> Double -> Double -> Double
cdf mu alpha beta x = 0.5 + signum(x - mu) * ( lowerGamma (1/beta) ((abs(x-mu) / alpha)**beta) / (2 * gamma(1/beta))) 
main = do
 let x = pdf 0 1 2 0.5
 print x
 let y = cdf 0 1 2 0.5
 print y
Malachi
29k11 gold badges86 silver badges188 bronze badges
asked Oct 28, 2013 at 3:40
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Your code looks fine to me. If you wish, you could use Greek letters. This makes the formula easier to read, but if you expect to modify it often, it may be too much trouble to enter the Greek letters. You might find it helpful to split up long formulas, as I've done for pdf. If you can think of more meaningful names than foo and bar, this might be a good idea. However, if this is a well-known formula in your field, splitting it up might actually make it less recognisable. It's a judgement call.

If you wrote this in literate Haskell, you could include a nicely-formatted version of the formula using LaTeX. That might be useful if you're writing code with a lot of formulas.

import Math.Gamma
γ :: Double -> Double
γ = gamma
pdf :: Double -> Double -> Double -> Double -> Double
pdf μ α β x = foo ** bar ** β
 where foo = ( β / (2 * α * γ ( 1/β) ) )
 bar = exp ( -1* ( abs(x - μ )/α ))
cdf :: Double -> Double -> Double -> Double -> Double
cdf μ α β x = 0.5 + signum(x - μ) * ( lowerGamma (1/β) ((abs(x-μ) / α)**β) / (2 * γ(1/β))) 
main = do
 let x = pdf 0 1 2 0.5
 print x
 let y = cdf 0 1 2 0.5
 print y
answered Nov 21, 2013 at 18:12
\$\endgroup\$
2
  • \$\begingroup\$ good review. I don't think putting greek letters into the code is a idea personally, but you explained that as well. again good review \$\endgroup\$ Commented Nov 21, 2013 at 18:53
  • \$\begingroup\$ The great letters are a great idea! as well as literate haskell. Now i just need to find out how to type them easily with my editor. \$\endgroup\$ Commented Nov 21, 2013 at 21:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.