使用何處和守衛
鑑於此功能:
annualSalaryCalc :: (RealFloat a) => a -> a -> String
annualSalaryCalc hourlyRate weekHoursOfWork
| hourlyRate * (weekHoursOfWork * 52) <= 40000 = "Poor child, try to get another job"
| hourlyRate * (weekHoursOfWork * 52) <= 120000 = "Money, Money, Money!"
| hourlyRate * (weekHoursOfWork * 52) <= 200000 = "Ri¢hie Ri¢h"
| otherwise = "Hello Elon Musk!"
我們可以使用 where
來避免重複並使我們的程式碼更具可讀性。使用 where
檢視下面的替代功能:
annualSalaryCalc' :: (RealFloat a) => a -> a -> String
annualSalaryCalc' hourlyRate weekHoursOfWork
| annualSalary <= smallSalary = "Poor child, try to get another job"
| annualSalary <= mediumSalary = "Money, Money, Money!"
| annualSalary <= highSalary = "Ri¢hie Ri¢h"
| otherwise = "Hello Elon Musk!"
where
annualSalary = hourlyRate * (weekHoursOfWork * 52)
(smallSalary, mediumSalary, highSalary) = (40000, 120000, 200000)
如上所述,我們在函式體的末尾使用了 where
,消除了重複計算(hourlyRate * (weekHoursOfWork * 52)
),我們還使用 where
來組織工資範圍。
使用 let
表示式也可以實現公共子表示式的命名,但只有 where
語法才能使警衛能夠引用那些命名的子表示式。