Haskell 函数定义中的代码缩进问题
Haskell's code indentation issue in function's definition
我试图在 Haskell 中编写合并排序代码,但出了点问题。
我觉得下面的代码应该是正确的
-- UPDATE : COMPLETE PROGRAMM'S CODE
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
| x <= y = x:merge xs (y:ys)
| otherwise = y:merge (x:xs) ys
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
where half = \xs -> div (length xs) 2
因为第一个 where 被称为“否则”行,所以缩进得比那行更远。
第二个 where 是指所有第一个“where 块”,因此它应该嵌套在第一个中。
编译时它给我这个错误
Variable not in scope: mergeSort
|
26 | mergeSort xs
| ^^^^^^^^^
所以函数的定义有问题。
我尝试以多种不同的方式修复布局,例如
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
where half = \xs -> div (length xs) 2
但其中 none 个有效。
我也在这里寻找解决方案,我发现了一些与我正在做的非常接近的东西 --> Haskell Merge Sort
它还提供了正确的代码
mergeSort merge xs
| length xs < 2 = xs
| otherwise = merge (mergeSort merge first) (mergeSort merge second)
where first = take half xs
second = drop half xs
half = length xs `div` 2
但这为什么有效?是不是需要一秒钟在哪里指定“一半”?为什么不存在?
无法理解为什么我的仍然无法正常工作。
在您的代码中 half 仅在 myright 定义中“可见”。
删除第二个 where
有效:
merge :: [a] -> [a] -> [a]
merge = undefined
mergeSort :: [a] -> [a]
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
half = \xs -> div (length xs) 2
我试图在 Haskell 中编写合并排序代码,但出了点问题。 我觉得下面的代码应该是正确的
-- UPDATE : COMPLETE PROGRAMM'S CODE
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
| x <= y = x:merge xs (y:ys)
| otherwise = y:merge (x:xs) ys
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
where half = \xs -> div (length xs) 2
因为第一个 where 被称为“否则”行,所以缩进得比那行更远。 第二个 where 是指所有第一个“where 块”,因此它应该嵌套在第一个中。 编译时它给我这个错误
Variable not in scope: mergeSort
|
26 | mergeSort xs
| ^^^^^^^^^
所以函数的定义有问题。 我尝试以多种不同的方式修复布局,例如
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
where half = \xs -> div (length xs) 2
但其中 none 个有效。
我也在这里寻找解决方案,我发现了一些与我正在做的非常接近的东西 --> Haskell Merge Sort 它还提供了正确的代码
mergeSort merge xs
| length xs < 2 = xs
| otherwise = merge (mergeSort merge first) (mergeSort merge second)
where first = take half xs
second = drop half xs
half = length xs `div` 2
但这为什么有效?是不是需要一秒钟在哪里指定“一半”?为什么不存在? 无法理解为什么我的仍然无法正常工作。
在您的代码中 half 仅在 myright 定义中“可见”。
删除第二个 where
有效:
merge :: [a] -> [a] -> [a]
merge = undefined
mergeSort :: [a] -> [a]
mergeSort xs
| length xs < 2 = xs
| otherwise = merge (mergeSort (myleft xs)) (mergeSort (myright xs))
where myleft xs = take (half xs) xs
myright xs = drop (half xs) xs
half = \xs -> div (length xs) 2