简体   繁体   中英

Haskell Instance of Num issue

What is wrong with this code?

rectangle :: Int -> Int -> String
rectangle i j
    | i < 0 || j < 0    = ""
    | otherwise         = concatenate(i) ++ "n/" ++ (rectangle i) j-1




concatenate :: Int -> String
concatenate i
    | i <= 0            = ""
    | otherwise         = "*" ++ concatenate(i-1)

This is the error I get

  ERROR line 3 - Instance of Num [Char] required for definition of rectangle

This is supposed to be what it does (for example)

Main> putStr (rectangle 3 4)
****
****
****

You will get used to Haskell syntax sooner or later. This here

(rectangle i) j-1

is parsed as

(rectangle i j) - 1

But you really want:

rectangle i (j-1)

This code should work.

rectangle :: Int -> Int -> String
rectangle i j
    | i < 0 || j < 0    = ""
    | otherwise         = concatenate i ++ "\n" ++ rectangle i (j-1)




concatenate :: Int -> String
concatenate i
    | i <= 0            = ""
    | otherwise         = "*" ++ concatenate (i-1)

Few comments on that:

concatenate(i) ==> concatenate i
-- You don't need to put parameters in brackets in haskell.
(rectangle i) j-1 ==> rectangle i (j-1)
-- See Ingo's explanation
"n/" ==> "\n"
-- That should be obvious

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM