jallexy
jallexy

Reputation: 23

How to apply function to nested list of String in Haskell?

I have parsed data from table (by tagSoup) and now i have nested list of data

datatable with type [[String]]

Now i want to save this data as list of objects [Obj] - lines of table. Each line consist of 5 Strings.

data Obj = Obj { pdDate :: String,
    pdTournamentId :: String,
    pdTournamentName :: String,
    pdOperation :: String,
    pdTown :: String }
    deriving (Eq,Show,Read)

And I have a function to create the Obj

buildObj [a:b:c:d:e] = do
    let lst = last e
    let line = Obj {pdDate = a,
    pdTournamentId = b,
    pdTournamentName = c,
    pdOperation  = d,
    pdTown  = lst}
    return line 

To pass through the nested list in the main block, I call the function map

    map buildObj datatable
  1. And how to save all the data Obj to list [Obj]?

I am very new in Haskell, so looking if anybody could give me pointers to it.

Thanks!

UPDATE: The answer of @Mark Seemann helped to fix error type [[[String]]]

current errors

 * Couldn't match expected type `Obj' with actual type `m0 Obj'
    * In a stmt of a 'do' block: return line

and

 * Couldn't match type `[]' with `IO'
      Expected type: IO Obj
        Actual type: [Obj]
    * In a stmt of a 'do' block: map buildObj datatable

Upvotes: 0

Views: 380

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233197

The pattern a:b:c:d:e matches a list with the head a and tail b:c:d:e.

The pattern b:c:d:e, likewise, would match a list with the head b and tail c:d:e.

Reducing further, the pattern d:e would match a list with the head d and the the tail e.

Thus, e is itself a list.

If you want to match on a list with exactly five elements, you can write it as

a:b:c:d:e:[]

or, alternatively

[a,b,c,d,e]

Notice that this is an incomplete pattern match. You should also consider what to do if the list is smaller or larger than exactly five elements.

Upvotes: 5

Related Questions