Haskell:列表中邻居号码之间的最小距离 [英] Haskell: min distance between neighbor numbers on a list
问题描述
我试图定义一个函数来找到列表中相邻数字之间的最小距离。
像这样:
minNeighborsDistance [2,3,6,2,0,1,9,8] => 1
我的代码如下所示:
minNeighborsDistance [] = []
minNeighborsDistance(x:xs)= minimum [minNeighborsDistance xs ++ [subtract x(head xs)]]
虽然这似乎是运行的,但是一旦我输入列表,我将收到一个异常错误。
我是Haskell的新手,希望对此有所帮助。
如果您将单例列表传递给 minNeighborsDistance
,则
- 在第一行中将无法匹配
[]
,然后 - 它将成功匹配
(x:xs)
将单个值赋给x
并且空格就像xs
,然后当你尝试访问头时它会抛出一个错误
此外,由于您调用 minNeighborsDistance
递归,那么你总是最终在单例列表中调用它,除了当你传递一个空列表时。
I'm trying to define a functino that finds the minimum distance between to neighbor numbers on a list
something like this:
minNeighborsDistance [2,3,6,2,0,1,9,8] => 1
My code looks like this:
minNeighborsDistance [] = []
minNeighborsDistance (x:xs) = minimum[minNeighborsDistance xs ++ [subtract x (head xs)]]
Although this seems to run, once I enter a list I receive an Exception error.
I'm new to Haskell I would appreciate any help in this matter.
If you pass a singleton list to minNeighborsDistance
then
- It'll fail to match
[]
in the first line, then - it'll successfully match
(x:xs)
assigning the single value tox
and the empty like toxs
, then - it'll throw an error when you try to access the
head
of an empty list.
Further, since you call minNeighborsDistance
recursively then you'll always eventually call it on a singleton list excepting when you pass it an empty list.
这篇关于Haskell:列表中邻居号码之间的最小距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!