mifun s = foldr op 0 s
where op x r = head x + r
有没有办法让 ghci 告诉我?
尝试:t mifun
(缩写:type mifun
)
这使
*Main> :t mifun
mifun :: (Num b) => [[b]] -> b
因此,对于b
的实例num
,mifun
获取列表的列表b
并输出单个b
(在本例中是列表的第一个元素的总和)。
这不是一个真正的答案,但我需要格式化。
注意: mifun
如果任何包含的列表为空,则为 ⊥。例如:
> mifun [[3], [5, 8], [], [1, 2, 3]]
*** Exception: Prelude.head: empty list
如果您希望上述示例的结果为 9(将空列表视为对总和没有贡献),则应将 op 定义为以下方式之一:
mifun s = foldr op 0 s
where op [] r = r
op (x:_) r = x + r
mifun s = foldr op 0 s
where op x r = (if null x then 0 else head x) + r
mifun s = foldr op 0 s
where op x r = sum (take 1 x) + r
我可能更喜欢第一个。