首页 > 解决方案 > Haskell中字符串列表的长度

问题描述

我不知道如何完成我的代码并需要帮助。

我需要的函数应该能够计算字符串列表中的字符数。

例如:

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)

这些是我拥有并且可以使用的功能:

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)

现在我需要第一个 List of StringscharLena和第二个 List of Strings的长度charLenb

我也被允许使用map和递归以及haskell的基本命令(没有其他)

但是如何通过 StrLst 数据类型进行映射?

标签: haskellrecursion

解决方案


StrLst不是列表,所以不能map直接使用。但是,您应该编写的两个函数似乎负责决定映射哪个列表:

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

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

ab是第一个和第二个列表,分别存储在StrLst作为参数接收的值中。每个都有类型[String],因此适合用作 的参数map


更新:由于您无法对StrLst值进行模式匹配,因此您无法直接访问任一列表。您唯一能做的就是使用lenalenb从任一列表中获取单个字符串的长度。为了知道哪些索引是 / 的有效参数lenalenb您需要使用numa/numb来查找任一列表的长度,然后构造一个范围。例如,[0..numa s - 1]会给你一个有效索引列表到s.

一旦你有了索引列表,你可以将部分应用的函数映射到lena s它上面,为你提供列表 A 的所有单独的字符串列表,然后你可以对这些列表进行总结,得到charLena.

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

charLenb将是相似的,但使用numbandlenb代替。


推荐阅读