Dear all,
I just started to learn Haskell with learnyouahaskell.com and at the very beginning, I met a strange issue with following simple function:
This function works as expected for positive arguments, e.g., "toZero 10" gives me [10,9,8,7,6,5,4,3,2,1,0]. However, GHCI will raise following error if I give it a negative argument, e.g., "toZero -10":
This seems strange to me as 10 and -10 has exactly the same type "Num a => a". I've done with chapter 1~10 of learnyouahaskell.com but still has no idea on why this error. Anybody can help to explain this? Thanks a lot. Regards Zhiyi Xie _______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners |
On 2016-02-08 17:24, wizard wrote:
> Dear all, > > I just started to learn Haskell with learnyouahaskell.com and at the very > beginning, I met a strange issue with following simple function: > > -- why does work with "toZero 10" but not for "toZero -10"? > toZero :: (Integral t) => t -> [t] [..] > This function works as expected for positive arguments, e.g., "toZero 10" > gives me [10,9,8,7,6,5,4,3,2,1,0]. However, GHCI will raise following error > if I give it a negative argument, e.g., "toZero -10": [..] The issue is that 'toZero -10' is parsed as 'toZero minus 10', i.e. it's not a negative value you're passing there. It expects 'toZero' to be a numeric value. Try toZero (-10) instead. -- Frerich Raabe - [hidden email] www.froglogic.com - Multi-Platform GUI Testing _______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners |
In reply to this post by wizard
If you are wondering why you are having this problem it is because - can be interpretted as either a one argument negation or a two argument subtraction. If you put parenthesis around (-n) where n is an integer, it will interpret it as unary, something that will not happen in other operators. >:t (-)(-) :: Num a => a -> a -> a >:t (+) (+) :: Num a => a -> a -> a >:t (-1) (-1) :: Num a => a >:t (+1) (+1) :: Num a => a -> a >:t (1-1) (1-1) :: Num a => a >:t (1+1) (1+1) :: Num a => a On Mon, Feb 8, 2016 at 11:24 AM, wizard <[hidden email]> wrote:
_______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners |
Thanks Frerich and David! I got it, :-) 2016-02-09 0:43 GMT+08:00 David McBride <[hidden email]>:
_______________________________________________ Beginners mailing list [hidden email] http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners |
Free forum by Nabble | Edit this page |