DEV Community

Brandon Rozek
Brandon Rozek

Posted on • Originally published at brandonrozek.com on

Real Analysis Sequences in Haskell

In Real Analysis it is useful to look at terms of a sequence. One of the best ways I’ve found to do this is in believe it or not Haskell. This is mainly for these two reasons

  • Support for infinite data structures

  • Built-in Data Type to keep fractional precision

Code

Let’s get started, first let us define a sequence by the following: $$ f(1) = 1, f(2) = 2, f(n) = \frac{1}{2}(f(n - 2) + f(n - 1)) $$ That is equivalent to the following haskell code:

f :: Integral a => a -> Ratio a
f 1 = 1
f 2 = 2
f n = 0.5 * (f (n - 2) + f (n - 1))

Enter fullscreen mode Exit fullscreen mode

Now to generate the sequence we just need to map $f$ onto the natural numbers.

nsequence = map f [1..]

Enter fullscreen mode Exit fullscreen mode

If you want to look at specific subsequences, such as even or odd:

odd_generator n = 2 * n - 1
odds = map odd_generator [1..]

even_generator n = 2 * n
evens = map odd_generator [1..]

Enter fullscreen mode Exit fullscreen mode

To look at the differences between each term:

diff x = map (\(a, b) -> a - b) $ zip (tail x) (init x)

Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay