Haskell:绑定模式匹配的地方
Haskell: where bindings pattern match
目前我正在尝试通过在线教程 Learn you a Haskell 学习 Haskell。在"Syntax in Functions"一章作者写了"You can also use where bindings to pattern match!"。之后是代码示例的一部分,但我不知道 where 模式匹配与新的 where 绑定一起使用。
因为代码块的第一部分被缩短了("We could have rewritten the where section of our previous function as"),你只能推断它,但我认为我选择了正确的部分。
函数:
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
要替换的新 where 部分:
where bmi = weight / height ^ 2
(skinny, normal, fat) = (18.5, 25.0, 30.0)
因为想看懂本教程讲解的Haskell的所有代码示例和语法方法,所以希望有人能解释一下这里用到模式匹配的地方,以及它是如何工作的。
对我来说,问题是我只看到守卫和一种将所有内容绑定到体重和身高的模式。
行
(skinny, normal, fat) = (18.5, 25.0, 30.0)
是一个模式绑定 -- 该模式是 (skinny, normal, fat)
,一个绑定三个名称的元组模式。您还可以在 where
(和 let
)中使用其他类型的模式,例如:
head' :: [a] -> a
head' list = x
where
x : xs = list
这里x : xs
是绑定两个名字的模式。当然在这种情况下是不必要的,我们可以将模式放在参数中。不过偶尔也能派上用场。
目前我正在尝试通过在线教程 Learn you a Haskell 学习 Haskell。在"Syntax in Functions"一章作者写了"You can also use where bindings to pattern match!"。之后是代码示例的一部分,但我不知道 where 模式匹配与新的 where 绑定一起使用。 因为代码块的第一部分被缩短了("We could have rewritten the where section of our previous function as"),你只能推断它,但我认为我选择了正确的部分。
函数:
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
要替换的新 where 部分:
where bmi = weight / height ^ 2
(skinny, normal, fat) = (18.5, 25.0, 30.0)
因为想看懂本教程讲解的Haskell的所有代码示例和语法方法,所以希望有人能解释一下这里用到模式匹配的地方,以及它是如何工作的。 对我来说,问题是我只看到守卫和一种将所有内容绑定到体重和身高的模式。
行
(skinny, normal, fat) = (18.5, 25.0, 30.0)
是一个模式绑定 -- 该模式是 (skinny, normal, fat)
,一个绑定三个名称的元组模式。您还可以在 where
(和 let
)中使用其他类型的模式,例如:
head' :: [a] -> a
head' list = x
where
x : xs = list
这里x : xs
是绑定两个名字的模式。当然在这种情况下是不必要的,我们可以将模式放在参数中。不过偶尔也能派上用场。