Haskell - 将函数作为参数传递

时间:2017-09-20 04:07:36

标签: function haskell arguments

所以在haskell中我有以下两个函数(它们只是执行一些数学运算)

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 - >浮动 - >浮点数,它从q和r计算其输出,这是cubicQ和cubicR的输出。我如何将函数cubicQ和cubicR作为参数q和r传递给cubicS?以下是我到目前为止所尝试的内容,但我很难过。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:3)

试试这个:

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 

或:

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

或:

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)

请参阅:

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

输出:

9.736999e-2

如果您将cubicS限制为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