簡體   English   中英

Haskell 中字符串列表的長度

[英]length of list of strings in 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)

現在我需要第一個字符串列表charLena和第二個字符串列表charLenb

我也被允許使用map和 recursion 以及 haskell 的基本命令(nothisng else)

但是如何通過 StrLst 數據類型進行映射?

StrLst不是列表,因此不能直接使用map 但是,您應該編寫的兩個函數似乎負責決定映射哪個列表:

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

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

ab分別是存儲在作為參數接收的StrLst值中的第一個和第二個列表。 每個都有類型[String] ,因此適合用作map的參數。


更新:由於您無法對StrLst值進行模式匹配,因此您無法直接訪問任一列表。 您唯一能做的就是使用lenalenb從任一列表中獲取單個字符串的長度。 為了知道哪些索引是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將類似,但使用numblenb代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM