[英]Haskell: What's the type of this function?
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
我可能更喜歡第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.