Jon
Jon

Reputation: 278

Haskell list within a list within a list

I am learning Haskell and I have a problem where if given a list of a list of a list of Strings I have to find the total number of Strings in the entire initial list. My though process was to convert the entire initial list into a one dimensional list and get the length, however I can seem to figure it out.

What I have so far:

type Word = String
type Line = [Word]
type Page = [Line]
type Doc = [Page]
numWords :: Doc -> Line -> Word -> Int

I need to find the number of Words and I'm not sure if this is even the best way to go about this type of problem, but I am at a loss for ideas.

Any help would be much appreciated. Thank you.

Upvotes: 0

Views: 125

Answers (1)

AJF
AJF

Reputation: 11923

This is quite a simple problem.

If we have a look at the types, it becomes easy:

type Word = String
type Line = [String]
type Page = [[String]]
type Doc  = [[[String]]]

It's not too difficult to get the length of a Line:

lenLine x = length x

The Page is just the sum of all the inner lengths:

lenPage xs = sum $ map lenLine xs

And we can use the same kind of pattern for Doc:

lenDoc xs = sum $ map lenPage xs

As for your final function , just use all the others:

numWords :: Doc -> Page -> Line -> Int
numWords dc pg ln = lenDoc dc + lenPage pg + lenLine ln

Remember that a type synonym doesn't mean that the type is actually different; you can use the same functions.

Upvotes: 1

Related Questions