获取错误 "Parse error in pattern: length Failed, modules loaded: none"
Getting error "Parse error in pattern: length Failed, modules loaded: none"
--To check the list is in ascending order or not
ascending::[Int]->Bool
ascending [] =True
ascending ((length l) == 1) =True
ascending l =((head l)<=l !! 1) && ascending(tail l)
这是我的 Haskell 代码,当我尝试在我的 GHCI 解释器中 运行 这段代码时,出现以下错误:
ascending.hs(File_name):4:13: Parse error in pattern: length
Failed, modules loaded: none.
谁能告诉我错误在哪里?
您不能在参数模式中放置条件。长度为 1 的列表的模式为 hd::[]
.
您似乎在尝试添加守卫。您需要将输入列表绑定到 l
并将条件分隔为 |
:
ascending :: [Int]->Bool
ascending [] =True
ascending l | ((length l) == 1) =True
ascending l = ((head l)<=l !! 1) && ascending(tail l)
您可以使用模式匹配代替对守卫 head
和 tail
的使用:
ascending :: [Int]->Bool
ascending [] = True
ascending [_] = True
ascending (x:y:xs) = (x <= y) && ascending (y:xs)
--To check the list is in ascending order or not
ascending::[Int]->Bool
ascending [] =True
ascending ((length l) == 1) =True
ascending l =((head l)<=l !! 1) && ascending(tail l)
这是我的 Haskell 代码,当我尝试在我的 GHCI 解释器中 运行 这段代码时,出现以下错误:
ascending.hs(File_name):4:13: Parse error in pattern: length
Failed, modules loaded: none.
谁能告诉我错误在哪里?
您不能在参数模式中放置条件。长度为 1 的列表的模式为 hd::[]
.
您似乎在尝试添加守卫。您需要将输入列表绑定到 l
并将条件分隔为 |
:
ascending :: [Int]->Bool
ascending [] =True
ascending l | ((length l) == 1) =True
ascending l = ((head l)<=l !! 1) && ascending(tail l)
您可以使用模式匹配代替对守卫 head
和 tail
的使用:
ascending :: [Int]->Bool
ascending [] = True
ascending [_] = True
ascending (x:y:xs) = (x <= y) && ascending (y:xs)