2013-06-01 60 views
3

我加載此文件作爲一個模塊來擁抱,但得到這個錯誤:擁抱不要讓腳本文件使用關鍵字「讓」

錯誤文件:\ Hugs.hs:38 - 語法錯誤輸入(意想不到的關鍵字「讓」)

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 

回答

2

刪除let

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

m = MetricMeasurement 2 Meter 
6

您不能有let語句在頂層。簡單地寫

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

正如其他人指出,不使用let一個頂級的定義,只是一個函數內局部定義。

我已經回答了,因爲我忍不住指出,您可以通過使用模式匹配來改善很多代碼。

對於symbol,匹配可以在頂層去:

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

而對於另外兩個,你可以使用一個case語句相匹配,對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)會類似。