interspersing a space in a string

Submitted by metaperl on Mon, 10/03/2005 - 12:44pm.

Cale gibbard came up with a Monad for interspering:

"hello" >>= (\x -> [x,' '])

but what if you don't want a trailing space?

Submitted by Cale Gibbard on Mon, 10/03/2005 - 9:48pm.

I posted that code because the space at the end was desired.

You can't tell the beginning of the string from the end in the function passed to bind, so you're stuck if you don't want any kind of postprocessing. You could just use List.intersperse, or take init of the result there.

The trouble is that the type of (>>=), specialised to this situation is [Char] -> (Char -> [Char]) -> [Char]. The function given as the second parameter doesn't get any context to tell it that it's at the last character.

You could do something like this:

intersperse' u xs = tails xs >>= f
f [] = []
f [x] = [x]
f (x:xs) = [x,u]

By first applying tails, you provide the extra context needed to make that decision, but the code becomes somewhat more complex.

Also, note that "the monad" refers to the type constructor, in this case, the list functor, which in Haskell is called "[]", and not the values contained in that type. Sort of a subtle distinction which people seem to often miss.

(by the way, what's with not allowing <pre> in Filtered HTML mode, or <p> in either mode? How are we supposed to have paragraphs and code together?)

- Cale

Submitted by dtlin on Tue, 10/04/2005 - 2:17pm.

These are what I've used.  Not the best of style, but you get the idea.

(>>= (:" "))         "hello" == "h e l l o "
List.intersperse ' ' "hello" == "h e l l o"

(>>= (++ " "))               ["hello", "and", "goodbye"] == "hello and goodbye "
unfoldl1 ((. (' ':)) . (++)) ["hello", "and", "goodbye"] == "hello and goodbye"

On the other hand, you could also use
init $ (>>= (:" ")) "hello" == "h e l l o"
because length " " == 1.

Submitted by Greg Buchholz on Mon, 10/17/2005 - 10:08am.

with a fold...

join j = foldr1 (\a b -> a ++ j ++ b)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.