Haskell if another list comprehension

I am trying to print the right board as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1. . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . 3. . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . 8. . . . . . . . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . . . . . . 11. . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . . . . . 13. . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . 15. . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . 18. . . . . . . . . . . . . . . . . . 

I have a list comprehension here

  ((concat [(""++show i)++" " | i <- [1..n], i<10])++"\n") 

I can correctly get the 9 first numbers, but the problem arises when I would like to put an else expression in my understanding. I don't seem to know how to do this. Therefore, to make myself clearer, I would like to do the same with double digits, but the only difference would be that I want two spaces instead of three between each double digit.

+5
source share
1 answer

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 &lt- [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 &lt- [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 &lt- [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" 
+2
source

Source: https://habr.com/ru/post/1273366/


All Articles