sep*_*eph 0 int haskell list char
假设我有一个像这样的列表:
list= [["a","123","b"],["h","435","t"],["w","234","j"]]
Run Code Online (Sandbox Code Playgroud)
我需要的是将该列表列表中的每个第二个成员转换为一个,Integer
因为它将在此之后用作大小指示符,因此我可以按大小对列表进行排序.
我想出了一个转换功能:
charToInt c = ord (chr c)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何转换列表中的每个第二个成员.
要扩展Paul Johnson所说的内容,您需要为要尝试保留的数据定义数据类型.
data MusicFile = MusicFile {music :: String,
size :: Integer,
artist :: String}
deriving Show
musicFileFromStrings :: [String] -> MusicFile
musicFileFromStrings [sMusic, sSize, sArtist]
= MusicFile sMusic (read sSize) sArtist
Run Code Online (Sandbox Code Playgroud)
然后,如果你有
list = [["a","123","b"],["h","435","t"],["w","234","j"]]
Run Code Online (Sandbox Code Playgroud)
你可以说
anotherList = map musicFileFromStrings list
Run Code Online (Sandbox Code Playgroud)
然后
map music anotherList -- ["a", "h", "w"]
map artist anotherList -- ["b", "t", "j"]
Run Code Online (Sandbox Code Playgroud)
(编辑)
如果要按特定字段对列表进行排序,可以使用"sortBy"和" 比较 ".
import Data.List
import Data.Ord
sizeOrderList = sortBy (comparing size) anotherList
Run Code Online (Sandbox Code Playgroud)
"比较"功能将值(在这种情况下为"大小")上的函数转换为两个值之间的比较函数.唯一的要求是"size"的输出(在这种情况下)是一个"Ord"实例的类型.
如果你想降序而不是使用
sizeOrderList = sortBy (comparing (flip size)) anotherList
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1006 次 |
最近记录: |