【问题标题】:How to apply function to nested list of String in Haskell?如何将函数应用于 Haskell 中的嵌套字符串列表?
【发布时间】:2019-05-09 20:20:46
【问题描述】:

我已经从表中解析了数据(通过 tagSoup),现在我有嵌套的数据列表

datatable with type [[String]]

现在我想将此数据保存为对象列表 [Obj] - 表格行。每行由 5 个字符串组成。

data Obj = Obj { pdDate :: String,
    pdTournamentId :: String,
    pdTournamentName :: String,
    pdOperation :: String,
    pdTown :: String }
    deriving (Eq,Show,Read)

我有一个创建 Obj 的函数

buildObj [a:b:c:d:e] = do
    let lst = last e
    let line = Obj {pdDate = a,
    pdTournamentId = b,
    pdTournamentName = c,
    pdOperation  = d,
    pdTown  = lst}
    return line 

要通过主块中的嵌套列表,我调用函数map

    map buildObj datatable
  1. 以及如何将所有数据 Obj 保存到列表 [Obj] 中?

我是 Haskell 的新手,所以看看是否有人可以给我指点。

谢谢!

更新:@Mark Seemann 的回答有助于修复错误类型 [[[String]]]

当前错误

 * Couldn't match expected type `Obj' with actual type `m0 Obj'
    * In a stmt of a 'do' block: return line

 * Couldn't match type `[]' with `IO'
      Expected type: IO Obj
        Actual type: [Obj]
    * In a stmt of a 'do' block: map buildObj datatable

【问题讨论】:

  • 您希望[a:b:c:d:e] 匹配什么?
  • @Rein Henrichs 我希望会有 5 个字符串,我只是不知道另一种方法来做到这一点
  • 所以如果数据表类型为 [[String]],我希望 [a:b:c:d:e] - [String] 我的初始表的一行
  • 显示产生错误的代码。
  • @chepner 我更新了问题描述。如果有任何提示,我将不胜感激!

标签: haskell


【解决方案1】:

a:b:c:d:e 模式匹配 listhead atail b:c:d:e

同样,b:c:d:e 模式将匹配具有 head btail c:d:e 的列表。

进一步减少,d:e 模式将匹配具有 head dtail e 的列表。

因此,e 本身就是一个列表。

如果你想匹配一个正好有五个元素的列表,你可以写成

a:b:c:d:e:[]

或者,或者

[a,b,c,d,e]

请注意,这是一个不完整的模式匹配。如果列表小于或大于恰好五个元素,您还应该考虑如何处理。

【讨论】:

  • 谢谢!这对我帮助很大!或许你可以对这个问题给出提示:how to save all the data Obj to list [Obj] after calling map buildObj datatable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2018-05-14
  • 2016-02-08
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多