Haskell 为什么head的返回值隐式转换为Maybe?
我刚刚开始学习Haskell,为了练习,我决定创建一个函数,它接受一棵树,树的元素具有位置和大小,并返回位于某个位置的元素。我的代码如下所示:Haskell 为什么head的返回值隐式转换为Maybe?,haskell,Haskell,我刚刚开始学习Haskell,为了练习,我决定创建一个函数,它接受一棵树,树的元素具有位置和大小,并返回位于某个位置的元素。我的代码如下所示: import Data.List (dropWhile) data Node = Node (Int,Int) (Int,Int) [Node] deriving(Eq, Show) findNode :: (Int,Int) -> Node -> Maybe Node findNode loc node@(Node (x, y) (wi
import Data.List (dropWhile)
data Node = Node (Int,Int) (Int,Int) [Node] deriving(Eq, Show)
findNode :: (Int,Int) -> Node -> Maybe Node
findNode loc node@(Node (x, y) (width, height) []) = if loc >= (x, y) && loc <= (x+width, y+height) then Just node else Nothing
findNode loc node@(Node (x, y) (width, height) children) =
if loc >= (x, y) && loc <= (x+width, y+height)
then if not $ null nodes then
head nodes
else
Just node
else Nothing
where nodes = dropWhile (==Nothing) $ map (findNode loc) children
导入数据列表(dropWhile)
数据节点=节点(Int,Int)(Int,Int)[节点]派生(Eq,Show)
findNode::(Int,Int)->节点->可能节点
findNode loc node@(node(x,y)(width,height)[])=如果loc>=(x,y)和&loc=(x,y)和&loc,这是因为您的节点具有[可能节点]
类型。实际上,您可以通过显式注释并再次编译来验证:
findNode loc node@(Node (x, y) (width, height) children) =
if loc >= (x, y) && loc <= (x+width, y+height)
then
if not $ null nodes
then head nodes
else Just node
else Nothing
where
nodes = dropWhile (==Nothing) $ map (findNode loc) children :: [Maybe Node]
findNode loc node@(节点(x,y)(宽度,高度)子节点)=
如果loc>=(x,y)和&loc b)->[a]->[b]
,在您的情况下,findNode loc
的类型是Node->Maybe Node
,因此结果类型是[Maybe Node
)。而dropWhile
的类型是(a->Bool)->[a]->[a]
。在你的例子中,a
已经是可能节点
,因此你的节点
有一种[可能节点]
的类型,这是因为你的节点
有一种[可能节点]
的类型。实际上,您可以通过显式注释并再次编译来验证:
findNode loc node@(Node (x, y) (width, height) children) =
if loc >= (x, y) && loc <= (x+width, y+height)
then
if not $ null nodes
then head nodes
else Just node
else Nothing
where
nodes = dropWhile (==Nothing) $ map (findNode loc) children :: [Maybe Node]
findNode loc node@(节点(x,y)(宽度,高度)子节点)=
如果loc>=(x,y)和&loc b)->[a]->[b]
,在您的情况下,findNode loc
的类型是Node->Maybe Node
,因此结果类型是[Maybe Node
)。而dropWhile
的类型是(a->Bool)->[a]->[a]
。在您的情况下,a
已经是Maybe节点
,因此您的节点
具有一种类型的[Maybe节点]@user467526您可能希望foldr()Nothing$map(findNode loc)子节点
只挑选列表中的第一个非空值(如果有),并且省去了if语句和where子句的麻烦。@user467526您可能希望foldr()Nothing$map(findNode loc)子项
只需在列表中选择第一个非空值(如果有),省去了if语句和where子句的麻烦。