[英]How to return different type in recursion function? (Haskell)
我需要在递归函数中返回例如整数或布尔值。
我的问题的示例代码:
findInt :: [Int] -> Either Int Bool
findInt (x:xs) =
if x == 1 then x
else False : findInt xs
然后错误提示无法将预期的类型“ Either Int Bool”与实际的类型“ Int”匹配 。 但是我想检查该元素是否在此列表中,如果存在,它将返回该元素,并通过返回布尔值告诉我是否不是。
如果您查看Either类型,则会看到它具有两个构造函数Left
和Right
。 为了构造Either
类型的值,您需要使用构造函数之一。 例如
if x == 1 then Left x
具体来说, Left
用于构造Either类型的第一种类型(在这种情况下为Int
),而Right
用于第二种类型(在这种情况下为Bool
)。
给定的函数没有类型: x :: Int
和(False : _) :: [Bool]
,并且这两种类型无法统一(将::
读作“具有类型”)。
进行了调整
findInt (x:xs) =
if x == 1 then Left x
else Right False : findInt xs
它仍然没有类型: Left x :: Either Int b
和(Right False : _) :: [Either a Bool]
,这两种类型也不能统一。
但
findInt :: [Int] -> Either Int Bool
findInt (x:xs) =
if x == 1 then Left x
else findInt xs
findInt [] = Right False
具有类型,因为Left x :: Either Int b
和Right False :: Either a Bool
,这两种类型可以统一:
Either Int b
Either a Bool
----------------- a ~ Int , b ~ Bool
Either Int Bool
统一类型的确是类型签名指定的Either Int Bool
。
由于您从未在输出中使用True
,因此您对Either Int Bool
使用与Maybe Int
同构:
a2b :: Either Int Bool -> Maybe Int
a2b (Right x) = Just x
a2b (Left x) = Nothing
b2a :: Maybe Int -> Either Int Bool
b2a (Just x) -> Right x
b2a Nothing -> Left False
因此,我只是使用Maybe Int
来简化您的功能。
findInt :: [Int] -> Maybe Int
findInt [] = Nothing
findInt (x:xs) = if x == 1 then Just x else findInt xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.