How to generate the alphabet with white space between letters?

Asked

Viewed 4,189 times

7

In Haskell I can generate the alphabet as follows:

alfabeto = ['a'..'z']

To display it is enough:

alfabeto

"abcdefghijklmnopqrstuvwxyz"

However, I would like to know how I can put a space between the letters, this way:

"a b c d e f g h ..."

Doubts

  1. Is there any way to do this?
  2. Is there a specific operator I can use? If so, how should I use it?
  • Doubt: the result should be "a b c ... z" or "a b c ... z ", with respect to the last space?

  • unwords [[x]|x <-['a'..'z']]

2 answers

5


The module Data.List has the function intersperse that does just that. See in Ghci:

Prelude> :m + Data.List
Prelude Data.List> intersperse ' ' ['a'..'z']
"a b c d e f g h i j k l m n o p q r s t u v w x y z"

3

If it is possible to keep the space at the end, after the character z, you can map the characters by concatenating with the white space and then merge everything into one string with unwords:

> unwords (map(: " ")['a'..'z'])
"a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z "

See working on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.