【问题标题】:length of list of strings in HaskellHaskell中字符串列表的长度
【发布时间】:2021-09-19 22:23:21
【问题描述】:

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

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

例如:

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)

现在我需要第一个字符串列表charLena 和第二个字符串列表charLenb 的长度。

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

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

【问题讨论】:

  • 那么你有什么尝试?你被困在哪里了?你不明白什么?我们愿意提供帮助,但这不是一项自行完成的服务。
  • 我不知道如何映射 StrLst 数据类型,因为这对我来说是新的

标签: haskell recursion


【解决方案1】:

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 和 lenb 代替。

【讨论】:

  • 非常感谢您的回答。
  • 我做了你推荐的charLenb(StrLst _ b) = lengthLst b 并且 LengthLst 是我编写的一个函数,用于计算 [String] 的长度,但它不起作用。我收到此错误“不在范围内:数据构造函数 `StrLst'”
  • 您是否从不导出数据构造函数的模块导入数据类型? StrLst 是您提供的类型定义中使用的名称。
  • 是的,我做到了import Types (StrLst, createStrLst, numa , numb, lena, lenb)
  • 好的,那么您似乎无法从值中获取单个列表,只能通过 lena 和 lenb 获取单个字符串长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2021-06-25
  • 1970-01-01
相关资源
最近更新 更多