Cindy
Cindy

Reputation: 41

Haskell - Passing a function as an argument

so in haskell I have the following 2 functions made (they are just performing some math operations)

cubicQ :: Float -> Float -> Float -> Float
cubicQ a b c = (3*a*c - b**2) / (9*a**2)

cubicR :: Float -> Float -> Float -> Float -> Float 
cubicR a b c d = (9*a*b*c - 27*(a**2)*d-2*b**3)

I am to make a third function cubicS that has a requirement that the function be of type Float -> Float -> Float and it calculates its output from q and r, which is the output for cubicQ and cubicR. How would I pass the functions cubicQ and cubicR as arguments q and r in cubicS? Below is what I have tried so far but I am stumped. Any help would be greatly appreciated.

cubicS q r = (r+ (q**3+r**2)**(1/2))**(1/3)
    where q = (cubicQ a b c d) 
          r = (cubicR a b c)

Upvotes: 2

Views: 2914

Answers (1)

wasmup
wasmup

Reputation: 16263

try this:

cubicQ a b c = (3*a*c - b**2) / (9*a**2)
cubicR a b c d = (9*a*b*c - 27*(a**2)*d-2*b**3)
cubicS q r  = (r+ (q**3+r**2)**(1/2))**(1/3)

f a b c d = cubicS (cubicQ a b c) (cubicR a b c d)

main = do print $   f 1 2 3 4 

or:

cubicS a b c d  = (r+ (q**3+r**2)**(1/2))**(1/3)
  where q = cubicQ a b c 
        r = cubicR a b c d

or:

cubicS a b c d =  
  let q = cubicQ a b c
      r = cubicR a b c d
  in (r+ (q**3+r**2)**(1/2))**(1/3)

see:

cubicQ :: Float -> Float -> Float -> Float
cubicQ a b c = (3*a*c - b**2) / (9*a**2)

cubicR :: Float -> Float -> Float -> Float -> Float 
cubicR a b c d = (9*a*b*c - 27*(a**2)*d-2*b**3)

cubicS :: Float -> Float -> Float -> Float -> Float 
cubicS a b c d =  
  let q = cubicQ a b c
      r = cubicR a b c d
  in 
    (r+ (q**3+r**2)**(1/2))**(1/3)

main = do print $ cubicS 1.1 2.2 3.3 4.4

output:

9.736999e-2

and if you restricted to cubicS being cubicS: Float -> Float -> Float:

cubicQ a b c = (3*a*c - b**2) / (9*a**2)
cubicR a b c d = (9*a*b*c - 27*(a**2)*d-2*b**3)
cubicS q r  = (r+ (q**3+r**2)**(1/2))**(1/3)

cureS a b c d =  cubicS q r 
    where q = cubicQ a b c
          r = cubicR a b c d

main = do print $ cureS 1.1 2.2 3.3 4.4

Upvotes: 3

Related Questions