Nask [Char]的Haskell实例需要定义getPara错误

时间:2012-04-16 16:04:48

标签: haskell

getPara :: (Num [Char])  =>  [Char] -> Integer -> [Char]
getPara "" _ = ""


getPara str nr 
    | (nr == 0 ) && ((head str) == ')' ) = ')' : getPara "" 0 
    | ( nr == 0 ) && ( (head str) == '(' ) = '(' : (getPara (tail str) 0)
    | (nr /= 0 ) && ( (head str) == '(') = (getPara (tail str) nr-1) 
    | (nr == 0 ) && ( (head str) /= '(' ) = (head str) : (getPara (tail str) 0 )
    | otherwise = (getPara (tail str) nr)

我想要做的是从String得到一组括号,我得到的错误是:

Illegal Haskell 98 class constraint in type declaration
*** Expression : getPara
*** Type       : Num [Char] => [Char] -> Integer -> [Char]

有什么问题?

2 个答案:

答案 0 :(得分:2)

不允许使用getPara的类型签名,但潜在的问题是您在定义的某个位置缺少括号。如果您将代码更改为:

getPara :: [Char] -> Integer -> [Char]
getPara "" _ = ""

getPara str nr 
    | (nr == 0 ) && ((head str) == ')' )  = ')' : getPara "" 0 
    | (nr == 0 ) && ( (head str) == '(' ) = '(' : (getPara (tail str) 0)
    | (nr /= 0 ) && ( (head str) == '(')  = (getPara (tail str) (nr-1))  -- here!
    | (nr == 0 ) && ( (head str) /= '(' ) = (head str) : (getPara (tail str) 0 )
    | otherwise = (getPara (tail str) nr)

它编译......但我不确定它是否有效。

有两处变化:

  1. getPara
  2. 的类型签名
  3. 中括号中的nr-1
    | (nr /= 0 ) && ( (head str) == '(')  = (getPara (tail str) (nr-1))
    

答案 1 :(得分:2)

从Matt的回答开始,让我们美化代码(但我没有检查它是否有效)。首先,列表的模式匹配比许多headtail好得多:

getPara :: [Char] -> Integer -> [Char]
getPara "" _ = ""
getPara (x:xs) nr 
    | (nr == 0 ) && ( x == ')' )  = ')' : getPara "" 0 
    | (nr == 0 ) && ( x == '(' ) = '(' : getPara xs 0
    | (nr /= 0 ) && ( x == '(' )  =  getPara xs (nr-1)  -- here!
    | (nr == 0 ) && ( x /= '(' ) = x : getPara xs 0 
    | otherwise = getPara xs nr

现在你可以进行更多的模式匹配:

getPara :: [Char] -> Integer -> [Char]
getPara "" _ = ""
getPara (')':xs) 0                 = ')' : getPara "" 0 
getPara ('(':xs) 0                 = '(' : getPara xs 0
getPara ('(':xs) nr   | nr /= 0    = getPara xs (nr-1)  -- here!
getPara (x:xs) 0      | x /= '('   = x : getPara xs 0 
getPara (_:xs) nr                  = getPara xs nr

<强> [编辑]

正如丹尼尔指出的那样,仔细分析会发现剩下的警卫总是如此。

getPara :: [Char] -> Integer -> [Char]
getPara "" _ = ""
getPara (')':xs) 0   = ')' : getPara "" 0 
getPara ('(':xs) 0   = '(' : getPara xs 0
getPara ('(':xs) nr  = getPara xs (nr-1)  -- here!
getPara (x:xs) 0     = x : getPara xs 0 
getPara (_:xs) nr    = getPara xs nr