无法将预期类型[a]与实际类型Maybe [a]相匹配

时间:2019-07-07 13:18:05

标签: haskell

请原谅新手水平的问题。

我现在正在尝试将Maybe引入我以前的帮助器功能(该功能交换列表的前两个元素)以启用空列表错误处理:

... haskell

JSONObject object = new JSONObject(response); JSONArray array=object.getJSONArray("result");

并在

中调用
-- | the helper funtion to only swap the first two elements.
swap_first_two_elements :: [a] -> Maybe [a]
swap_first_two_elements list = case list of
  x:y:xs -> Just (y:x:xs)
  _      -> Nothing

但是我收到类似

的错误
 interprete s x

  | x `elem` ["+","-","*","/","^"] = operate x s
  | x `elem` ["inc","dec","sqrt","sin","cos","inv"] =  operate2 x s
  | x `elem` ["+all"] =  [sum s]
  | x `elem` ["dup"] =  (head s) :s
  | x `elem` ["pop"] =   tail s
  | x `elem` ["swap"] =    swap_first_two_elements s
  | x `elem` ["clear"] =  drop (length s) s
  | x `elem` ["*all"] =  [product s]
  | otherwise = read x:s
  where
    operate op (x:y:s) = case op of
      "+" -> x + y:s
      "-" -> y - x:s
      "*" -> x * y:s
      "/" -> y / x:s
      "^" -> y ** x:s

我阅读了其他相关文章并对其进行了修改,例如:

  Couldn't match expected type [a] with actual type Maybe[a]

仍然出现错误。专家能提供我哪里出错了吗?谢谢。

2 个答案:

答案 0 :(得分:3)

所以你有

interprete s x
  | x `elem` ["pop"]  =   tail s
  | x `elem` ["swap"] =   swap_first_two_elements s

现在

tail                    :: [a] ->       [a]

但是

swap_first_two_elements :: [a] -> Maybe [a]

当然,它们是两种不同的类型。

在某些情况下,您不能返回一种类型的值,而在其他情况下,则不能完全返回另一种类型的值。函数定义中的所有情况都必须返回 same 类型的值。

函数从类型变为类型,而不是类型

您可以通过将所有其他案例的值包装在Just中来固定定义,如下所示:

  | x `elem` ["pop"]  =   Just (tail s)

答案 1 :(得分:0)

只是为了让您的代码更有意义,我认为您需要将Maybe散布到所有子功能中,例如在operate,pop和所有其他“不安全”功能中,您可以利用Maybe类型,像除以0:

interprete s x
                | x `elem` ["+","-","*","/","^"] = operate x s
                | x `elem` ["inc","dec","sqrt","sin","cos","inv"] = Just (operate2 x s)
                | x `elem` ["+all"] =  Just([sum s])
                | x `elem` ["dup"] = dup s
                | x `elem` ["pop"] = pop s 
                | x `elem` ["swap"] = swap_first_two_elements s
                | x `elem` ["clear"] = Just []
                | x `elem` ["*all"] = Just([product s])
                | otherwise = Just(read x:s)

pop [] = Nothing
pop (x:xs) = Just xs

dup [] = Nothing
dup s@(x:xs) = Just (x:s) 

operate op (x:y:s) = case op of
  "+" -> Just(x + y:s)
  "-" -> Just(y - x:s)
  "*" -> Just( x * y:s)
  "/" -> case x of 
        0  -> Nothing
        n  -> Just(y / x:s)
  "^" -> Just(y ** x:s)
operate _ _ = Nothing

swap_first_two_elements :: [a] -> Maybe [a]
swap_first_two_elements (x:y:xs)  = Just (y:x:xs)
swap_first_two_elements _ = Nothing

operate2 = undefined

我不知道operate2是做什么的,所以,我留给您。但是可以肯定的是,它的类型为[a]-> Maybe [a],所以请使其返回Maybe [a]。