拥抱不要让脚本文件使用关键字“让”

时间:2013-06-01 04:03:51

标签: haskell hugs

我将此文件作为模块加载到Hugs,但出现此错误:

错误文件:。\ Hugs.hs:38 - 输入中的语法错误(意外关键字“let”)

data MetricUnit = Meter
            | Liter
            | KiloGram
              deriving (Show, Eq)

data ImperialUnit = Yard
              | Gallon
              | Pound
                deriving (Show, Eq)

data Measurement = MetricMeasurement Double MetricUnit
             | ImperialMeasurement Double ImperialUnit
               deriving (Show)

symbol :: MetricUnit -> String
symbol x
  | x == Meter = "m"
  | x == Liter = "L"
  | x == KiloGram = "kg"

convert (MetricMeasurement x u)
  | u==Meter    = ImperialMeasurement (1.0936*x) Yard
  | u==Liter    = ImperialMeasurement (0.2642*x) Gallon
  | u==KiloGram = ImperialMeasurement (2.2046*x) Pound

convert (ImperialMeasurement x u)
  | u==Yard   = MetricMeasurement (0.9144*x) Meter
  | u==Gallon = MetricMeasurement (3.7854*x) Liter
  | u==Pound  = MetricMeasurement (0.4536*x) KiloGram

let fac n = if n == 0 then 1 else n * fac (n-1)   --This line doesn't work
let m = MetricMeasurement 2 Meter

3 个答案:

答案 0 :(得分:6)

您无法在顶级发布let条款。只需写下

fac n = if n == 0 then 1 else n * fac (n-1)
m = MetricMeasurement 2 Meter

答案 1 :(得分:2)

删除let

fac n = if n == 0 then 1 else n * fac (n-1)

m = MetricMeasurement 2 Meter

答案 2 :(得分:1)

正如其他人所指出的那样,您不会将let用于顶级定义,仅用于函数中的本地定义。

我已经回答了,因为我忍不住指出你可以通过使用模式匹配来改进你的许多代码。

对于symbol,匹配可以位于顶层:

symbol :: MetricUnit -> String
symbol Meter = "m"
symbol Liter = "L"
symbol KiloGram = "kg"

对于其他两个,您可以使用案例陈述来匹配u,如下所示:

convert (MetricMeasurement x u) = case u of
   Meter    -> ImperialMeasurement (1.0936*x) Yard
   Liter    -> ImperialMeasurement (0.2642*x) Gallon
   KiloGram -> ImperialMeasurement (2.2046*x) Pound

convert (ImperialMeasurement x u)类似。