我是Haskell的新手,并实现了计算BMI(身体质量指数)的功能.但我必须采取两种方式:
-- Calculate BMI using where clause
:{
calcBmis :: (RealFloat a) => [(a, a)] -> [a]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
:}
-- Input: calcBmis [(70, 1.7), (90, 1.89)]
-- Output: [24.221453287197235, 25.195263290501387]
Run Code Online (Sandbox Code Playgroud)
和
-- Calculate BMI using just list comprehension
:{
calcBmis :: (RealFloat a) => [(a, a)] -> [a]
calcBmis xs = [bmi w h | (w, h) <- xs]
bmi weight height = weight / height ^ 2
:}
-- Input: calcBmis [(70, 1.7), (90, 1.89)]
-- Output: [24.221453287197235, 25.195263290501387]
Run Code Online (Sandbox Code Playgroud)
两者都很完美!唯一的区别是where
在第一个使用.我已经看到,where
如果我必须声明常量或多个函数,哪个是好的.我不知道是否存在另一种方式使用它一段时间,但直到现在我才学到这样的东西.
我是否想知道这两个函数之间的区别是干净的代码,还是在这种情况下还有更特殊的东西?
使用where
块和创建新的顶级声明之间有两个主要区别.
确定新定义变量的范围.一个where
块的范围比顶级声明更有限:在你的例子中,对于where
块,我不能bmi
从外部调用实现calcBmis
,但是我可以使用额外的顶级声明.
确定定义中可用的变量的范围.where
块中的定义可以看到所定义函数的本地变量名.在您的示例中,虽然您没有使用此事实,但bmi
可以xs
在where
-block版本中看到该名称; 新的顶级声明没有xs
范围.因此,当将where
-block定义提升到顶层时,有时需要向它们添加额外的参数,并在调用它们时将局部变量作为参数传递.