【问题标题】:Struggling with lists in Haskell在 Haskell 列表中苦苦挣扎
【发布时间】:2014-11-17 15:07:40
【问题描述】:

我在使用 Haskell 中的列表时遇到问题。

这是我的功能:

create_matrix :: (Read t, Integral t) => [String] -> t -> [[t]]
create_list_of_lists (x:xs) num = [read x `div`z | z <- [1..num]] : create_list_of_lists xs num

当我这样运行时:

create_list_of_lists ["1212","3232"] 3

我得到了想要的输出,即

[[1212,606,404],[3232,1616,1077]

但它最后错过了最后一个 ']',并显示此错误:

Exception: hondt.hs:39:1-81: Non-exhaustive patterns in function create_list_of_lists

我猜这与类型有关,但我不知道我做错了什么。

【问题讨论】:

    标签: haskell


    【解决方案1】:

    发生的情况是,由于 Haskell 的懒惰,GHCi 在收到前两个子列表时会打印出来,但随后会出现错误。此错误是因为您尚未为create_list_of_lists 定义所有可能的输入,即当第一个参数为空时。你需要

    create_list_of_lists [] num = ???
    create_list_of_lists (x:xs) num = [read x `div`z | z <- [1..num]] : create_list_of_lists xs num
    

    如果没有[] 的子句,您最终将调用create_list_of_lists [] num,目前尚未定义。

    【讨论】:

    • 谢谢,我只需要覆盖空列表的情况。毕竟这么简单。
    • @dcarou 作为后续,每当您看到“函数中的非详尽模式...”时,这意味着您在某个地方漏掉了一个案例。如果您使用ghc -Wall 编译代码(打开所有警告),那么 GHC 可以告诉您缺少哪些案例,这也包括警卫和案例声明。我 100% 的时间都在使用 -Wall,它有助于发现这些小错误以及许多其他可能的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2014-05-11
    • 2013-02-20
    相关资源
    最近更新 更多