The left side of the list comprehension accepts any Haskell expression, so we can write if - then - else in the left hand of the list comprehension and omit the condition i < 10 on the right side
concat [(""++show i)++ if i < 10 then " " else " " | i <- [1..n]]++"\n"
For n = 15 this gives:
Prelude> concat [(""++show i)++if i < 10 then " " else " " | i <- [1..n]]++"\n" "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \n"
We can also remove the ""++ part on the left side of the list comprehension, as this is the basic operation no:
concat [show i ++ if i < 10 then " " else " " | i <- [1..n]] ++ "\n"
The above, however, is not very elegant: if i = 123 , then we will still encounter problems. We can calculate the length of the show , calculate 4-l (with l length) and add this as an extra interval. For instance:
concat [ s ++ replicate (4-length s) ' ' | i <- [1..n], let s = show i ] ++ "\n"
There are a few more special formatting and attachment functions, but since this exercise is likely to become more popular on lists, I think there isnβt enough scope here.
Like @ 4castle, we can use, for example, printf :
import Text.Printf(printf) concatMap (printf "%-4d") [1..n] ++ "\n"
source share