0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! The data type stuff is very confusing for me as I'm coming from Java. It seems very different.
@Jon Don't worry about it - it grows on you :)
Indeed it does grow on you. :) After using Haskell for a while, you'll find Java more and more unwieldy.
@Jon keep in mind that having numWords take a document and a page and a line might be triple-counting some lines depending on what you pass it. The simplest way is to just use the lenDoc function AJ gave, unless you have some specific need to do something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.