Haskell finds the value of a convergent sequence

Brand new for Haskell. I play with a Fibonacci sequence to learn the basics of the language, and I cannot find an idiomatic way to do something.

The Fibonacci sequence can be defined as follows:

fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

(This is already pretty cool). Then I want to use the sequence to approximate the ratio of Gold (Phi). So:

ratios = zipWith (/) (tail fibs) fibs

- A list of the best and best Phi approximations. Let's say I want to get the first value when the list has “stabilized” under the given epsilon threshold. (i.e. the difference between two consecutive relationship values ​​is less than epsilon). I can see how I will do it in an imperative language (using indexes), but how would I do it idiomatically in Haskell?

(Do I need to use the following list? But how?)

diffs = zipWith (-) ratios (tail ratios)
+4
2

? zip. , , :

snd . head . dropWhile (\(p1,p0) -> abs (p0 - p1) >= epsilon) $ zip ratio (tail ratio)

:

  • zip
  • , , epsilon
  • , .
+3

:

getApprox threshold = head $ [ratio | (ratio, diff) <- zip (tail ratios) diffs
                                    , abs diff < threshold
                             ]
+3

Source: https://habr.com/ru/post/1657530/


All Articles