簡體   English   中英

如何將函數應用於向量列表?

[英]How to apply function to vector list?

我有一個大的嵌套向量,如下所示:

import Data.Vector
let x = fromList [["a", "b", "12", "d"], ["e", "f", "34", "g"]...]

我想將字符串轉換為每個嵌套列表中位置2的整數,我試圖用map和這樣的理解來做到這一點:

let y = Data.Vector.map (\a -> read a :: Int) [i !! 2 | i <- x]

我究竟做錯了什么? 我希望輸出為:

(("a", "b", 12, "d"), ("e", "f", 34, "g")...)

這里有很多問題。

首先,列表Data.Vector.map的結果是一個列表,所以你在列表上調用Data.Vector.map ,這是行不通的。 理解中的xVector ,這是另一種類型不匹配。 使用列表而不是Vector(以及Prelude.map )或將列表轉換為Vector (在這種情況下,您不能使用列表Prelude.map )。

其次,忽略list / Vector問題, [i !! 2 | i <- x] [i !! 2 | i <- x] [i !! 2 | i <- x]將為您提供一個列表,其中僅包含每個子列表中位置2的元素。 使用你的例子,理解將產生["12", "34"] 然后當你對它進行地圖read時,你會獲得[12, 34] ,而不是你正在拍攝的輸出。

最后,您想要查看的輸出對於列表或Haskell中的Vectors無效。 兩種類型的容器必須是同質的,即它們不能包含多於一種類型的值。 [Int]不能包含String[String]也不能包含Int ,但是你想要的輸出包含兩者。 有一些方法可以使用存在類型來解決這個問題,但是對於您的潛在問題而言,有可能比嘗試構建異構集合更好。

編輯:您編輯了帖子的最后一部分以使用元組,因此上面的段落不再適用。 不過,我提到的前兩個問題仍然存在。

如果你從一個4元組列表開始( [(String, String, String, String)] ),你可以得到你想要的東西:

> let x = [("a", "b", "12", "d"), ("e", "f", "34", "g")]
> map (\(a, b, c, d) -> (a, b, read c :: Int, d)) x
[("a", "b", 12, "d"), ("e", "f", 34, "g")]

看起來你應該使用比4元組更復雜的數據類型

data YourType_StringNum = YourType_StringNum { ytsnLetters1 :: String
                                             , ytsnLetters2 :: String
                                             , ytsnNumber :: String
                                             , ytsnLetters3 :: String }
data YourType_IntNum = YourType_IntNum { ytinLetters1 :: String
                                       , ytinLetters2 :: String
                                       , ytinNumber :: Int
                                       , ytinLetters3 :: String }

(當然有更好的標識符)。 然后定義一個類似的函數

toYtin :: YourType_StringNum -> YourType_IntNum
toYtin(YourType_StringNum a b s c) = YourType_IntNum a b (read s) c

有了它,你的問題減少了將Vector YourType_StringNum轉換為Vector YourType_IntNum ,而這通過Data.Vector.map toYtin完成。

暫無
暫無

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

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