无法用 where 和 pattern match 解释 Haskell 代码
Trouble explaining Haskell code with where and pattern match
我很难解析 mf
m
y
是如何赋值的,甚至为什么 where
部分赋值的左侧可以有 3 个变量.
问:有人能解释一下这两种情况下发生了什么吗?(即空列表和包含一些元素的列表)
-- | A variant of 'foldl' that has no base case,
-- and thus may only be applied to non-empty structures.
--
-- @'foldl1' f = 'List.foldl1' f . 'toList'@
foldl1 :: (a -> a -> a) -> t a -> a
foldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure")
(foldl mf Nothing xs)
where
mf m y = Just (case m of
Nothing -> y
Just x -> f x y)
(这是source code for the foldl1
function)。
where
子句中的定义遵循与全局定义相同的语法,因此 mf m y = ...
定义了一个名为 mf
的函数,它采用名为 m
和 [=14 的参数=].
在空列表的情况下,根据定义 foldl mf Nothing [] ~ Nothing
,因此 foldl1
将 return 出现 "empty structure"
错误。
当xs
不为空时,foldl1'
只是foldl
的左折。在这种情况下 foldl
具有类型
foldl :: (Maybe a -> a -> Maybe a) -> Maybe a -> [a] -> Maybe a
它利用了 where
子句中定义的组合函数 mf :: Maybe a -> a -> Maybe a
。
I have hard time parsing how mf m y are assigned values or even why there can be 3 variables.
这里不定义三个变量:你定义一个变量mf
是一个函数,m
和y
是两个参数 函数 mf
.
我们可以让函数更优雅,从而省略m
和y
。 mf
可以定义为:
mf Nothing = Just . id
mf (Just x) = Just . f x
请注意,我们不能简单地使mf
成为一个外部函数,因为它使用了一个函数f
,它的参数是foldl1
。所以我们把它放在 where
子句中:
foldl1 :: (a -> a -> a) -> t a -> a
foldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure")
(foldl mf Nothing xs)
where mf Nothing = Just . id
mf (Just x) = Just . f x
我很难解析 mf
m
y
是如何赋值的,甚至为什么 where
部分赋值的左侧可以有 3 个变量.
问:有人能解释一下这两种情况下发生了什么吗?(即空列表和包含一些元素的列表)
-- | A variant of 'foldl' that has no base case,
-- and thus may only be applied to non-empty structures.
--
-- @'foldl1' f = 'List.foldl1' f . 'toList'@
foldl1 :: (a -> a -> a) -> t a -> a
foldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure")
(foldl mf Nothing xs)
where
mf m y = Just (case m of
Nothing -> y
Just x -> f x y)
(这是source code for the foldl1
function)。
where
子句中的定义遵循与全局定义相同的语法,因此 mf m y = ...
定义了一个名为 mf
的函数,它采用名为 m
和 [=14 的参数=].
在空列表的情况下,根据定义 foldl mf Nothing [] ~ Nothing
,因此 foldl1
将 return 出现 "empty structure"
错误。
当xs
不为空时,foldl1'
只是foldl
的左折。在这种情况下 foldl
具有类型
foldl :: (Maybe a -> a -> Maybe a) -> Maybe a -> [a] -> Maybe a
它利用了 where
子句中定义的组合函数 mf :: Maybe a -> a -> Maybe a
。
I have hard time parsing how mf m y are assigned values or even why there can be 3 variables.
这里不定义三个变量:你定义一个变量mf
是一个函数,m
和y
是两个参数 函数 mf
.
我们可以让函数更优雅,从而省略m
和y
。 mf
可以定义为:
mf Nothing = Just . id
mf (Just x) = Just . f x
请注意,我们不能简单地使mf
成为一个外部函数,因为它使用了一个函数f
,它的参数是foldl1
。所以我们把它放在 where
子句中:
foldl1 :: (a -> a -> a) -> t a -> a
foldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure")
(foldl mf Nothing xs)
where mf Nothing = Just . id
mf (Just x) = Just . f x