Haskell在计算最小值时减少所有元素。

huangapple go评论96阅读模式
英文:

Haskell decrease all elements while computing minimum

问题

我必须编写一个Haskell函数 shiftToZero :: (Num a, Ord a) => [a] -> [a],它接受一个列表并构建一个新列表,其中的元素减去最小值。

这个函数不应该多次访问列表元素(充分利用惰性计算)。

例如:shiftToZero [5,4,2,6] -> [3,2,0,4]

有解决这个问题的建议吗?

英文:

I have to write an Haskell function shiftToZero :: (Num a, Ord a) => [a] -> [a] that given a list constructs a new list that contains the elements decreased by the minimum value.

The function should not visit list elements more than once (take advantage of laziness).

For example: shiftToZero [5,4,2,6] -> [3,2,0,4]

Any suggestion to resolve this?

答案1

得分: 1

I'll give a hint, by way of a simpler problem to solve first. I would like to have a helper function with the type helper :: (Num a, Ord a) => (a, [a]) -> (a, [a]). The helper should return the same answer as this function:

inefficientHelper (x, xs) = (minimum xs, map (\x' -> x'-x) xs)

The problem with inefficientHelper is that it computes its two answers in two separate passes, so it could never be a component that we could use in implementing the function you care about. So your first task is to implement helper to return the right value (as specified by this inefficient implementation), but while making only one pass over the list xs.

Presumably this is being given as an exercise in some teaching material, and so the most recent material will have other examples of tying the knot that can serve as a hint for what comes after that. But if not, then have a Google -- there's lots of writing floating around on "tying the knot".

英文:

I'll give a hint, by way of a simpler problem to solve first. I would like to have a helper function with the type helper :: (Num a, Ord a) => (a, [a]) -> (a, [a]). The helper should return the same answer as this function:

inefficientHelper (x, xs) = (minimum xs, map (\x' -> x'-x) xs)

The problem with inefficientHelper is that it computes its two answers in two separate passes, so it could never be a component that we could use in implementing the function you care about. So your first task is to implement helper to return the right value (as specified by this inefficient implementation), but while making only one pass over the list xs.

Presumably this is being given as an exercise in some teaching material, and so the most recent material will have other examples of tying the knot that can serve as a hint for what comes after that. But if not, then have a Google -- there's lots of writing floating around on "tying the knot".

huangapple
  • 本文由 发表于 2023年3月10日 00:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定