简体   繁体   中英

length of list of strings in Haskell

I have no Idea how to complete my code and need help.

The function I need should be able to calculate the number of characters in a list of strings.

For example:

charLena (createStrLst ["avd", "d4sf"] ["asvd","a2e","bdsh"])    --output is 7 (Total length of the first List)

charLenb (createStrLst ["avd", "d4sf"] ["asvd","a2e","bdsh"])    --output is 11 (Total length of the second List)

Those are the functions I have and can use:

data StrLst = StrLst [String] [String] deriving (Eq)
StrLst :: [String] -> [String] -> StrLst 

createStrLst :: [String] -> [String] -> StrLst 
numa :: StrLst -> Int             --number of strings in a
numb :: StrLst -> Int             --number of strings in b
lena :: StrLst -> Int -> Int      --length of (i+1)-th string in a
lenb :: StrLst -> Int -> Int      --length of (i+1)-th string in b

createStrLst  a b = (StrLst a b)
numa (StrLst a b) = length a
numb (StrLst a b) = length b
lena (StrLst a b) i = length (a!!i)
lenb (StrLst a b) i = length (b!!i)

Now I need the length of the first List of Strings charLena and the second List of Strings charLenb .

I am also allowed to use map and recursion and just basic commands of haskell (nothisng else)

But how can I map through StrLst datatype??

StrLst is not a list, so you can't use map directly. However, the two functions you are supposed to write appear responsible for deciding which list to map over:

charLena :: StrLst -> Int
charLena (StrLst a _) = ...

charLenb :: StrLst -> Int
charLenb (StrLst _ b) = ...

a and b are the first and second lists, respectively, stored in the StrLst value received as an argument. Each has type [String] , and so is suitable for use as an argument to map .


Update: Since you don't have the ability to pattern match on the StrLst value, there is no way for you to get direct access to either list. The only thing you can do is use lena and lenb to get lengths of individual strings from either list. In order to know what indices are valid arguments to lena / lenb , you need to use numa / numb to find the length of either list, then construct a range. For example, [0..numa s - 1] would give you a list of valid indices into the first list of s .

Once you have the index list, you can map the partially applied function lena s over it to give you all the individual string lists for list A, which you can then sum up to give you the return value of charLena .

charLena s = let indices = [0..numa s - 1]
                 lengths = ... -- use map here
             in ...  -- add up the values in lengths here.

charLenb will be similar, but using numb and lenb instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM