Haskell:列表中邻居号码之间的最小距离 [英] Haskell: min distance between neighbor numbers on a list

查看:95
本文介绍了Haskell:列表中邻居号码之间的最小距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个函数来找到列表中相邻数字之间的最小距离。

像这样:

  minNeighborsDistance [2,3,6,2,0,1,9,8] => 1 

我的代码如下所示:

  minNeighborsDistance [] = [] 
minNeighborsDistance(x:xs)= minimum [minNeighborsDistance xs ++ [subtract x(head xs)]]

虽然这似乎是运行的,但是一旦我输入列表,我将收到一个异常错误。



我是Haskell的新手,希望对此有所帮助。

解决方案

如果您将单例列表传递给 minNeighborsDistance ,则


  1. 在第一行中将无法匹配 [] ,然后

  2. 它将成功匹配(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

  1. It'll fail to match [] in the first line, then
  2. it'll successfully match (x:xs) assigning the single value to x and the empty like to xs, then
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆