1

嗨,我自己无法弄清楚,我也无法在网上找到示例

我正在尝试使用可能或警卫,而我发现的示例只有两个变量,当我编辑或遵循示例时,我得到一个错误,这就是我想要做的

--maybe example
    Fun :: Double -> Double -> Double -> Maybe Double
    Fun a b c
        | a >= -1.0 || a <= 1.0 || b >= -1.0 || b <=1.0 || c /=0 || c >= -1.0 = Nothing
        | otherwise = Just max(  ((c^ (-c)) +   (a^(-c)-1.0)  ^   (a+ (-1.0/a)))     0.0)

gchi 出错

 The function `Just' is applied to two arguments,
    but its type `a0 -> Maybe a0' has only one

而 hlint 给出

No suggestions

尝试使用警卫代替我得到一个不同的错误

--guard example
    Fun :: Double -> Double -> Double -> Maybe Double
    Fun a b c
        | a >= -1.0 || a <= 1.0 || b >= -1.0 || b <=1.0 || c /=0 || c >= -1.0 = error "Value out of range "
        | otherwise = max(  ((c^ (-c)) +   (a^(-c)-1.0)  ^   (a+ (-1.0/a)))     0.0)

还有 ghc 和 hlints 错误

  test.hs:10:1:
        Invalid type signature: Fun :: Double
                                       -> Double -> Double -> Maybe Double
        Should be of form <variable> :: <type>
    $ hlint test.hs
 Error message:
  Left-hand side of type signature is not a variable: Fun
Code:
    Fun :: Double -> Double -> Double -> Maybe Double
  > Fun a b c
4

2 回答 2

7

您必须使用小写字母编写函数。这意味着写这个:

fun :: Double -> Double -> Double -> Maybe Double
fun a b c ...

函数永远不能以大写字母开头,因为大写标识符是为模块(Data.List例如)和类型构造函数和数据构造函数(如Intor Maybeor Just)和其他一些东西保留的。

Just您对构造函数的应用也有问题。如果你这样写:

Just max(something)

...它的含义与以下内容相同:

Just max something

即你给出了Just两个论点。您需要通过调整括号来解决此问题:

Just (max something)
于 2012-05-24T16:49:47.487 回答
3

语法错误,主要是:

f :: Double -> Double -> Double -> Maybe Double
f a b c
    |  a >= -1
    || a <=  1
    || b >= -1
    || b <=  1
    || c /=  0
    || c >= -1
     = Nothing

    | otherwise
     = Just $ max ((c ** (-c)) + (a ** (-c)-1) ** (a+ (-1/a))) 0

请注意使用更一般类型的指数运算符 ,(**)$避免Just包装器中的括号覆盖max.

于 2012-05-24T16:51:19.570 回答