haskell - Why is the return value of head implicitly converted to Maybe? -
i've started learn haskell , practice i've decided create function takes tree, elements have position , size, , returns element located @ position. code looks this:
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) node else nothing findnode loc node@(node (x, y) (width, height) children) = if loc >= (x, y) && loc <= (x+width, y+height) if not $ null nodes head nodes else node else nothing nodes = dropwhile (==nothing) $ map (findnode loc) children
this code compiles , runs far can tell, i'm curious 1 thing, why head nodes
acceptable instead of just $ head nodes?
.
that's because nodes
has type of [maybe node]
. can infact verify annotating explicitly , compiling again:
findnode loc node@(node (x, y) (width, height) children) = if loc >= (x, y) && loc <= (x+width, y+height) if not $ null nodes head nodes else node else nothing nodes = dropwhile (==nothing) $ map (findnode loc) children :: [maybe node]
so how does, nodes
have [maybe node]
type ?
the type of map (findnode loc) children
[maybe node]
. (general type of map map :: (a -> b) -> [a] -> [b]
, in case type of findnode loc
node -> maybe node
, hence resultant type [maybe node
] ). , type of dropwhile
(a -> bool) -> [a] -> [a]
. in case a
maybe node
, hence nodes
has type of [maybe node]
.
Comments
Post a Comment