haskell - 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 数据类型进行映射?
解决方案
StrLst
不是列表,所以不能map
直接使用。但是,您应该编写的两个函数似乎负责决定映射哪个列表:
charLena :: StrLst -> Int
charLena (StrLst a _) = ...
charLenb :: StrLst -> Int
charLenb (StrLst _ b) = ...
a
和b
是第一个和第二个列表,分别存储在StrLst
作为参数接收的值中。每个都有类型[String]
,因此适合用作 的参数map
。
更新:由于您无法对StrLst
值进行模式匹配,因此您无法直接访问任一列表。您唯一能做的就是使用lena
并lenb
从任一列表中获取单个字符串的长度。为了知道哪些索引是 / 的有效参数lena
,lenb
您需要使用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
将是相似的,但使用numb
andlenb
代替。
推荐阅读
- powershell - 使用 PowerShell 在 IIS 中启用可选功能
- python - 了解 Python 内置函数如何映射到底层 C 实现
- linux - 错误“分段错误(核心转储)”是什么意思?
- python - Python Gsutil Google SDK 外壳
- php - Symfony\Component\HttpKernel\Exception\NotFoundHttpException
- sql - 如何在 `where` 条件下使用连接
- xml - SED:如何使用 sed 在 xml 中注释和取消注释多行
- anylogic - Anylogic消息动画
- groovy - 以日期格式显示单引号
- c# - 自定义控制按钮 C# UWP