为什么这是一个非详尽的搜索模式?

时间:2014-01-13 01:41:28

标签: haskell recursion

为什么这不是详尽的,不丢弃元素意味着这应该最终停止?

do_something :: [(String, String, Int)] -> String
do_something [(a, b, c)] = func(a, b, c) ++ do_something( drop 1 [(a, b, c)])

1 个答案:

答案 0 :(得分:7)

您必须在(String, String, Int)声明中指定do_something列表的每个案例。您必须给出传递给do_something的参数为空或包含多于1个元素的定义。当您没有指定这些情况时,编译器不知道自动执行的操作。

另一种看待它的方法是函数声明中的模式匹配与使用case语句相同:

do_something :: [(String, String, Int)] -> String
do_something xs = case xs where
    [(a, b, c)] -> func (a, b, c) ++ do_something (drop 1 [(a, b, c)])
    -- What about the other cases?
    -- otherwise -> ???

此外,在这种情况下,将您的功能指定为

要好得多
do_something (x:xs) = func x ++ do_something xs
do_something [] = ???

因为这实际上是递归地定义了函数。表达式drop 1 [(a, b, c)]与仅编写[]相同,因此您当前的定义等同于

do_something [(a, b, c)] = func (a, b, c) ++ do_something []