Haskell how to transform a Char list into a Matrix?

0

My goal is the following:

They give me a list of Char, for example:

["++++.++++.++."]

What I want to achieve is to separate that list into small lists (put together a matrix) of Whole numbers, where each positive number will represent the sum of '+' and the negative number -1 the '.' '

Following the example of the list I gave, the matrix should be like this:

[[4],[-1],[4],[-1],[2],[-1]]

Use GHCi, version 8.2.1

For now I have:

compararChar :: (Char, Char) -> Bool
compararChar (c1, c2) = if c1==c2 then True else False

contarCaracteresHastaElPunto :: [Char] -> Int
contarCaracteresHastaElPunto [] = 0
contarCaracteresHastaElPunto (x:y) = if (compararChar(x, '.') /= True) then 1 + contarCaracteresHastaElPunto(y) else contarCaracteresHastaElPunto(y)
-- *Main> contarCaracteresHastaElPunto ("+++..")
-- 3

The function countCharactersAndThePoint I did it to see if it returned at least the first sum of '+' to find the first point '.'

Unfortunately, even that did not work out for me. Since if it happened:

("+++ ..") returns me the number 3, that's fine, but if I pass it for example ("+++. ++"), it will return 5, that is, it adds all the characters of the chain instead of adding the first 3.

I calculate that the problem is in else of if , but I do not know how to leave it empty.

If some haskell guru can give me a hand with all this mambo, I would be very grateful!

    
asked by Oren Diaz 24.11.2017 в 20:13
source

1 answer

1

The Data.List module has the function group , which receives a list of comparable elements and returns a list of lists where each sublist of the result contains only the same elements:

Data.List> group "+++.++.+."
["+++",".","++",".","+","."]

Given a sublist (which will contain only + or . ) we must return:

  • a list containing a single sublist indicating the number of + of the substring,
  • or a list that contains a sublist [-1] for each . ,

for which we create the following auxiliary function:

g :: String -> [[Int]]
g xs@('.':_) = replicate (length xs) [-1]
g xs = [[length xs]]

Finally, we create the function that groups the characters in sublists ( group ), maps each list with the auxiliary function g ( map g ) and concatenates all the lists ( concat ):

import Data.List(group)

f :: String -> [[Int]]
f = concat . (map g) . group

For example:

ghci> f "+++.++.+."
[[3],[-1],[2],[-1],[1],[-1]]
    
answered by 25.11.2017 / 12:02
source