Haskell where块中的If语法
我可以在where块中使用if语法吗?在下面的例子中,定义了Haskell where块中的If语法,haskell,Haskell,我可以在where块中使用if语法吗?在下面的例子中,定义了second的second where块中的if会产生一个解析错误,我无法理解 data Label = A | B | C deriving (Show) type Path = ([(Label, Int)],Int) data Section = Section { getA :: Int, getB :: Int, getC :: Int } deriving (Show) getPath :: Section -> (
second
的second where块中的if
会产生一个解析错误,我无法理解
data Label = A | B | C deriving (Show)
type Path = ([(Label, Int)],Int)
data Section = Section { getA :: Int, getB :: Int, getC :: Int } deriving (Show)
getPath :: Section -> (Path, Path) -> (Path, Path)
getPath () (Section a b c) = go
where
go ((toppath,top),(bottompath,bottom))
|top<c+bottom = ((A,a):toppath,top+a, second)
|otherwise = ((A,a):(C,c):bottompath,bottom+c+a, second)
where second =
if (bottom<c+top)
then ((B,b):bottompath,bottom+a)
else ((A,b):(C:c):toppath,top+c+a)
data Label=A | B | C派生(显示)
类型路径=([(标签,Int)],Int)
数据段=段{getA::Int,getB::Int,getC::Int}派生(Show)
getPath::Section->(路径,路径)->(路径,路径)
getPath()(部分a b c)=go
哪里
go((顶部路径,顶部),(底部路径,底部))
|top您可以,但是您应该在的where
范围内缩进if
,以便:
getPath :: Section -> (Path, Path) -> (Path, Path)
getPath () (Section a b c) = go
where
go ((toppath,top),(bottompath,bottom))
|top<c+bottom = ((A,a):toppath,top+a, second)
|otherwise = ((A,a):(C,c):bottompath,bottom+c+a, second)
where second =
if (bottom<c+top) -- ← extra indentation
then ((B,b):bottompath,bottom+a)
else ((A,b):(C:c):toppath,top+c+a)
getPath::Section->(路径,路径)->(路径,路径)
getPath()(部分a b c)=go
哪里
go((顶部路径,顶部),(底部路径,底部))
|另一方面,()
对于节类型的参数或(路径,路径)
类型的参数都无效。作为初学者,我发现通常在布局关键字后加上换行+缩进更容易避免缩进错误(where
,do
,let
,of
)而不必担心对齐问题。在这里,这只意味着在where
和second
之间放置一个换行符,并相应地缩进。或者,您可以始终使用显式{}
块和;
分隔符,但是(不幸的是)没有选项要求它们。谢谢,我还没有注意到它们。哈哈。为什么我必须缩进if两次?我看不到任何对齐。if的缩进必须比的结尾缩进得多,其中@松鼠你可能想读一篇短文。@Sir4ur0n不止一次,对吗?它必须缩进到第一次之外它正在定义的名称的字符。