[Haskell-beginners] making function problem (chapter 6 of Programming in Haskell)

Daniel Seidel ds at iai.uni-bonn.de
Tue Aug 9 16:11:27 CEST 2011


On Tue, 2011-08-09 at 13:37 +0000, Roelof Wobben wrote:
> 
> 
> ----------------------------------------
> > Subject: RE: [Haskell-beginners] making function problem (chapter 6 of Programming in Haskell)
> > From: ds at iai.uni-bonn.de
> > To: rwobben at hotmail.com
> > Date: Tue, 9 Aug 2011 15:33:19 +0200
> >
> > On Tue, 2011-08-09 at 13:15 +0000, Roelof Wobben wrote:
> > > Lets make a try
> > >
> > >
> > >
> > > ( ^) :: Int -> Int -> Int
> > >
> > > ^ x 0 = 1
> > >
> > > ^ x y = x + x ^ (y-1)
> > >
> > nearly perfekt, only syntax for (^) is still not ok. You would have
> > noticed when compiling.
> > The "^" is by default infix (like "+"), because its a symbol and not
> > starting with a letter (the exact specification you can look up in your
> > book I think, or in the Haskell report).
> > If you want to use is prefix, like a "normal" function, then you have to
> > put it in brackets, ie. write (^).
> > So either write
> >
> > (^) x 0 = 1
> > (^) x y = x * (x ^ (y-1))
> >
> > or (I think this works as well)
> >
> > x ^ 0 = 1
> > x ^ y = x * (x ^ (y-1))
> >
> > Please notice also the extra brackets around x ^ (y-1) in my definition.
> > You may not know the precedence of * and ^.
> > If you eliminate the brackets, make sure you gave the right priority to
> > ^, that the program does not calculate (x * x) ^ (y-1).
> >
> > And, last but not least a second typo: why do you use "+" in your
> > definition of the power?
> >
> 
> 
> because of this 
> 
>  
> 
> 4 * 3 = 4 + 4 + 4 
> 
>  
> 
> so the forumala on the second run would be  4 + 4* 3 
> 
>  
> 
Ok, I thought just the name of the function was a bit misleading,
because "positivePower" should have been named "product". The power
function is:

4 ^ 3 = 4 * 4 * 4

and the special case (if you want to handle 0 and not 1 as base case)

4 ^ 0 = 1


Cheers, Daniel.




More information about the Beginners mailing list