tags:

views:

162

answers:

2
mifun s = foldr op 0 s
          where op x r = head x + r 

Is there a way to make ghci tell me?

+11  A: 

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).

Andrew Jaffe
+1  A: 

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.

MtnViewMark
Actually, if you define an instance of Num that is lazy enough, `mifun [[3::MyLazyNum], [5, 8], [], [1, 2, 3]] >= 8` could be evaluated to true without causing an exception, so it might be more accurate to say "The result of `mifun` *contains* ⊥ if any of the contained lists is empty".
sepp2k
True enough - I can think of even more instances with bizarre behavior in this case... However, given the focus of the original question, I'd bet they are working with standard Num instances, and I wanted to point out a potential pitfall of the function itself.
MtnViewMark