Alan Rodriguez
Alan Rodriguez

Reputation: 9

How can I read a sentence, separate the words and apply my function to each word? Haskell

I have a function that reads a word, separates the first and the last letter and the remaining content mixes it and at the end writes the first and last letter of the word but with the mixed content.

Example: Hello -> H lle o

But I want you to be able to read a phrase and do the same in each word of the sentence. What I can do?

import Data.List
import System.IO 
import System.Random
import System.IO.Unsafe
import Data.Array.IO
import Control.Monad
import Data.Array

oracion = do 
 frase <- getLine
 let pL = head frase
 let contentR = devContent frase
 charDisorder <- aleatorio contentR
 let uL = last frase
 putStrLn $ [pL] ++ charDisorder ++ [uL]

aleatorio :: [d] -> IO [d]
aleatorio xs = do
        ar <- newArray n xs
        forM [1..n] $ \i -> do
            t <- randomRIO (i,n)
            vi <- readArray ar i
            vt <- readArray ar t
            writeArray ar t vi
            return vt
  where
    n = length xs
    newArray :: Int -> [d] -> IO (IOArray Int d)
    newArray n xs =  newListArray (1,n) xs

devContent :: [Char] -> [Char]
devContent x = init (drop 1 x)

Upvotes: 0

Views: 85

Answers (1)

bartop
bartop

Reputation: 10315

That should go like this:

doStuffOnSentence sentence = mapM aleatorio (words sentence)

Whenever You are dealing with monads (especially IO) mapM is real lifesaver.

What's more, if You want to concatenate the final result You can add:

concatIoStrings = liftM unwords
doStuffAndConcat = concatIoStrings . doStuffOnSentence

Upvotes: 1

Related Questions