1

I made the following code:

formateaAux2::[String] -> [String]
formateaAux2 xs = map (++ " ") xs

formateaAux1::[String] -> Int -> [String]
formateaAux1 xs n 
            |n > 0 = do 
                       x <- (formateaAux2(take n xs)) ++ (drop (length(xs) - n) xs)
                       formateaAux1 x (n - length(xs)) -- where it errors
            |n <= 0 = []
formateaAux1 [] _ = []

The purpose of these functions is the following:

  • formateaAux2 takes a list of strings and adds a blank space " " to each element in it. (works OK)
  • formateaAux1 is supposed to take a list of strings and a number, and use formateaAux2 on n words. If n is greater than the number of words in the list, it'll repeat the same process until n = 0.

Imagine the list of strings is ["Hello", "World"] and n is 4, the objective would be to have as output ["Hello ", "World "], with two blank spaces after each word. If n were 3, then only "Hello" would have two spaces after it, "World" only have one.

So far so good, but I'm getting the following type error telling me that in formateaAux1 x (n - length(xs)), the code expects x to be of type [String] and yet it only gets String. However x should be of type [String] since I'm concatenating a list made from formateaAux2 (which returns [String]) and the higher order function drop, right?

Been at this for a while and I don't know where to look at anymore (though it's probably something trivial), any help is appreciated!

4
  • What do you want for formateaAux1 ["a","b","c","d","e"] 17? I’m guessing you would want the result to be ["a ","b ","c ","d ","e "], but some confirmation would be nice. Commented Dec 11, 2020 at 13:25
  • @bradrn Yep, that'd be the expected output Commented Dec 11, 2020 at 13:26
  • 5
    Use let x = ... in ..., not do x <- ... -- you are not working with monads here. In your code x <- list means "take any one element of list" instead of "take the whole list". Commented Dec 11, 2020 at 13:26
  • @chi Understood, forgot about that. Thank you! Commented Dec 11, 2020 at 13:27

1 Answer 1

2

Thanks to what @chi said:

formateaAux2::[String] -> [String]
formateaAux2 xs = map (++ " ") xs


formateaAux1::[String] -> Int -> [String]
formateaAux1 xs n 
            |n > 0 = let x = (formateaAux2(take n xs)) ++ (drop n xs) in
                       formateaAux1 x (n - length(xs))
            |n <= 0 = xs
formateaAux1 [] _ = []
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.