开发者

Haskell: What's the type of this function?

开发者 https://www.devze.com 2022-12-25 09:45 出处:网络
mifun s = foldr op 0 s where op x r = head x + r Is the开发者_Python百科re a way to make ghci tell me?try :t mifun (short for :type mifun)
mifun s = foldr op 0 s
          where op x r = head x + r 

Is the开发者_Python百科re a way to make ghci tell me?


try :t mifun (short for :type mifun)

which gives

*Main> :t mifun
mifun :: (Num b) => [[b]] -> b

So, for a b an instance of num, mifun takes a list of lists of b and outputs a single b (which in this case is the sum of the first elements of the lists).


This isn't really an answer, but I needed the formatting.

N.B.: mifun is ⊥ if any of the contained lists is empty. For example:

> mifun [[3], [5, 8], [], [1, 2, 3]]
*** Exception: Prelude.head: empty list

If you want the result of the above example to be 9 (treating an empty list as not contributing to the sum), then you should define op as one of the following ways:

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 

I'd probably prefer the first.

0

精彩评论

暂无评论...
验证码 换一张
取 消