Haskell - 类型/模式匹配

时间:2013-02-21 18:15:49

标签: haskell types pattern-matching

以下代码无法编译。我收到类型错误。我认为这将是更好的版本,因为它清楚地分离了两个不同的情况...... 该函数有助于确定有限状态机是否接受输入字。

import Text.Show.Functions
import qualified Data.Set as Set
import qualified Data.List as List

setTransition :: (Int -> Char -> [Int])  -> [Int] -> Char -> [Int]
setTransition delta [] sigma            = []
setTransition delta xs@[x:xs'] sigma    = foldl f [] xs
                where f ys q = (delta q sigma) `List.union` ys

然而,这(删除模式匹配)会编译。有人能告诉我为什么吗?

import Text.Show.Functions
import qualified Data.Set as Set
import qualified Data.List as List

setTransition :: (Int -> Char -> [Int])  -> [Int] -> Char -> [Int]
setTransition delta [] sigma            = []
setTransition delta xs sigma    = foldl f [] xs
                where f ys q = (delta q sigma) `List.union` ys

帮助

1 个答案:

答案 0 :(得分:6)

您遇到语法错误:

xs@[x:xs']

应该是

xs@(x:xs')

但实际上你并不需要两种情况,因为

foldl f b [] = b

所以

foldl f [] [] = []

正如您的空列表案例所需。

事实上,在[]上使用(x:xs)并使用xxs进行模式匹配的foldl模式匹配非常罕见 - 这就是我所知道的在这两种情况下,{{1}}都会给你正确的答案。但它偶尔会发生。