Python vs Haskell in Monadic Operation

Python Functional programming library: Functools

Let’s explore how to use the functools module in Python to create a simple monadic behavior. While Python doesn’t enforce monads as strictly as Haskell, we can still demonstrate some functional concepts.

  1. Caching with @cache (formerly @lru_cache):
  • The @cache decorator allows you to create a lightweight function cache. It memoizes results, speeding up calculations.
  • Here’s an example using the Fibonacci series: from functools import cache @cache def fibonacci(n: int) -> int: if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(10)) # Cached result: 55 print(fibonacci(5)) # Cached result: 5
  • The @cache decorator ensures that previously computed results are reused, avoiding redundant calculations⁴.
  1. Maybe-Like Behavior:
  • While not a strict monad, we can create a simple “Maybe-like” behavior using a custom class: class Maybe: def __init__(self, value): self.value = value def map(self, func): if self.value is not None: return Maybe(func(self.value)) else: return Maybe(None)
  • def add_one(x): return x + 1
  • def double(x): return x * 2
  • maybe_result = Maybe(3).map(add_one).map(double) print(maybe_result.value) # Result: 8
  • maybe_none = Maybe(None).map(add_one).map(double) print(maybe_none.value) # Result: None
  • In this example, the Maybe class wraps a value and applies functions only if the value is not None³.

Remember that Python’s approach to monads is more flexible and pragmatic, but Haskell remains the gold standard for enforcing functional purity and type safety. 🌟🐍🔗

Source: Conversation with Copilot, 6/6/2024
(1) 6 Cool Things You Can Do With The Functools Module. https://pybit.es/articles/6-cool-things-you-can-do-with-the-functools-module/.
(2) ArjanCodes | Python Functors and Monads: A Practical Guide. https://www.arjancodes.com/blog/python-functors-and-monads/.
(3) functools — Higher-order functions and operations on … – Python. https://docs.python.org/3/library/functools.html.
(4) A short, hands-on introduction to Functors and Monads using Python. https://medium.com/@oikonomod/a-short-hands-on-introduction-to-functors-and-monads-using-python-6544b5739f3d.
(5) Functools module in Python – GeeksforGeeks. https://www.geeksforgeeks.org/functools-module-in-python/.

Comonad Use

Certainly! Let’s incorporate a simple example of a comonad in Haskell. While the Maybe monad is more commonly discussed, we can create a comonad-like behavior using the Store Comonad.

  1. Store Comonad:
  • The Store comonad represents a value with an associated context (or “store”). It allows us to extract information from the context.
  • We’ll create a basic Store comonad that holds a value and its index in a list.
  1. Example:

import Control.Comonad -- Define a Store comonad data Store s a = Store [a] s instance Functor (Store s) where fmap f (Store xs s) = Store (fmap f xs) s instance Comonad (Store s) where extract (Store xs s) = xs !! s duplicate (Store xs s) = Store (Store <$> tails xs <*> pure s) s -- Example usage main :: IO () main = do let myList = [10, 20, 30, 40, 50] store = Store myList 2 -- Value 30, index 2 putStrLn $ "Extracted value: " ++ show (extract store) putStrLn $ "Context (duplicated): " ++ show (duplicate store)

  • In this example:
    • We define a Store data type that holds a list of values and an index.
    • The Functor instance applies a function to each value in the list.
    • The Comonad instance provides extract (to get the current value) and duplicate (to create a new Store with all possible contexts).
    • We create a Store with the value 30 (index 2) and demonstrate extraction and duplication.

Remember that comonads are less commonly used than monads, but they provide a dual perspective on context and computation. 🌟🐦🔗 Let me know if you’d like further details or additional examples! 😊

Certainly! Let’s incorporate a simple example of a comonad in Haskell. While the Maybe monad is more commonly discussed, we can create a comonad-like behavior using the Store Comonad.

  1. Store Comonad:
  • The Store comonad represents a value with an associated context (or “store”). It allows us to extract information from the context.
  • We’ll create a basic Store comonad that holds a value and its index in a list.
  1. Example:

import Control.Comonad -- Define a Store comonad data Store s a = Store [a] s instance Functor (Store s) where fmap f (Store xs s) = Store (fmap f xs) s instance Comonad (Store s) where extract (Store xs s) = xs !! s duplicate (Store xs s) = Store (Store <$> tails xs <*> pure s) s -- Example usage main :: IO () main = do let myList = [10, 20, 30, 40, 50] store = Store myList 2 -- Value 30, index 2 putStrLn $ "Extracted value: " ++ show (extract store) putStrLn $ "Context (duplicated): " ++ show (duplicate store)

  • In this example:
    • We define a Store data type that holds a list of values and an index.
    • The Functor instance applies a function to each value in the list.
    • The Comonad instance provides extract (to get the current value) and duplicate (to create a new Store with all possible contexts).
    • We create a Store with the value 30 (index 2) and demonstrate extraction and duplication.

Remember that comonads are less commonly used than monads, but they provide a dual perspective on context and computation. 🌟🐦🔗 Let me know if you’d like further details or additional examples! 😊

What Makes Functional and Object-oriented Programming Equal

http://codinghelmet.com/articles/what-makes-functional-and-object-oriented-programming-equal

Comparison of 4 Functional Programming (FP : F#, Lisp/Clojure Haskell, Scala,… ) concepts in Object-Oriented (OO: C#, C++, Java,… ) :

[Not covered here] : There are other FP techniques lacking in OO: Functor (FoldMap), Monad, etc.

1. Function:

2. Closure (variable binding)

3. Currying

4. Function Composition

Conclusion:

A Programmer’s Regret: Neglecting Math at University – Adenoid Adventures

Advanced Programming needs Advanced Math: eg.

Video Game Animation: Verlet Integration

AI: Stats, Probability, Calculus, Linear Algebra

Search Engine : PageRank: Linear Algebra

Abstraction in Program “Polymorphism” : Monoid, Category, Functor, Monad

Program “Proof” : Propositions as Types, HoTT

https://awalterschulze.github.io/blog/post/neglecting-math-at-university/

Abstraction: Monoid, Category

Category

A Functional Programmer’s Guide to Homotopy Type Theory (HoTT)

Since April 2019 until I re-visit this Youtube video on 12 August 2019, I can now totally understand his speech after a pause of 4 months by viewing other related Youtube (below prerequisite) videos on Category Theory, Type Theory, Homotopy Type Theory.

That is the technique of self-study:

  1. First go through the whole video,
  2. Don’t understand? view other related simpler videos.
  3. Repeat 1.

Prerequisite knowledge:

  1. Homotopy
  2. Type Theory
  3. Homotopy Type Theory
  4. Bijection = Isomorphism
  5. Functional Programming in Category Theory Concept: Monad & Applicative

Two Key Takeaway Points:

  1. In the Homotopy “Space” : Programs are points in the space, Paths are Types.
  2. “Univalence Axiom” : Paths Induce Bijection, vice versa.

Knowing Monads Through The Category Theory

https://dev.to/juaneto/knowing-monads-through-the-category-theory-1mea

While Mathematicians like to talk non-sensical abstract idea, Informaticians want to know how to apply the idea concretely:

Mathematical Parlance:

Monad = Monoid +Endofunctor

Monoid = Identity + Associative

Endo-functor = functor between 2 same categories

IT Parlance:

Monad is a ‘function’ to wrap the ‘side effects’ (exception errors, I/O,… ) so that function composition in ‘pipeline‘ chained operation sequence is still possible in pure FP (Functional Programming, which forbids side-effects).

Some common Monads: ‘Maybe’, ‘List’, ‘Reader’…
This allows monads to simplify a wide range of problems, like handling potential undefined values (with the Maybe monad), or keeping values within a flexible, well-formed list (using the List monad). With a monad, a programmer can turn a complicated sequence of functions into a succinct pipeline that abstracts away additional data management, control flow, or side-effects.[2][3]

Exploring Monads in Scala Collections

https://blog.redelastic.com/a-guide-to-scala-collections-exploring-monads-in-scala-collections-ef810ef3aec3

Alejandro Serrano: Category Theory Through Functional Programming

(Part 1/3) – λC 2017

What is Category ?

Objects

Morphism (Arrows )

Rule1: Associative

Rule 2: Identity

A <– C –> B

Product of Categories : A x B

Unique

Sum of Categories: A + B

Unique

(Either a b)

Co-Product

Reverse all arrows.

Unique

Functor F: C-> D

Mapping of all objects (A, B) in categories C,D

Mapping of arrows f
f : A -> B
Ff : FA -> FB (preservation)
F Id = Id
F (f。g) = Ff。Fg

Example:

Constant C -> F
FC = k
Ff = Id

Arrow Functor F: C -> D

For any object A in C,

F A = D -> A
(Functional Type is also Type)

Functors compose !

Category of categories:

Objects: categories

Arrows : Functors

Haskell Category (Hask) is always Endo-Functor, ie Category Hask to itself.

Mapping of arrows.

Mapping of Objects = predefined

(Part 2/3) – λC 2017

(part 3/3) – λC 2017

Higher Order Function

[Source] https://www.quora.com/What-are-the-mathematical-explanations-for-higher-order-functions-Functional-programming/answer/Bartosz-Milewski?share=d265e0ac&srid=ZyHj

As Tikhon Jelvis explained in his response, functions map sets to sets, and functions themselves form sets. This is the essence of the untyped lambda calculus. Unfortunately, untyped lambda calculus suffers from the Kleene–Rosser paradox (later simplified to Curry’s paradox).

This paradox can be removed by introducing types, as in the typed lambda calculus. Simple types are equivalent to sets, but  in order to pass a function as an argument to another function (or return one), we have to give this function a type. To really understand what a function type is, you need to look into category theory.

The categorical model for the typed lambda calculus is a category in which objects are types and morphism are functions. So if you want to have higher order functions, you have to be able to represent morphisms as objects — in other words, create a type for functions. This is possible only if the category is cartesian closed. In such a category you can define product types and exponential types. The latter correspond to function types.

So that’s a mathematical explanation for higher order.

BM Category Theory : Motivation and Philosophy

Object-Oriented  has 2 weaknesses for Concurrency and Parallel programming : 

  1. Hidden Mutating States; 
  2. Data Sharing.

Category Theory (CT): a higher abstraction of all different Math structures : Set , Logic, Computing math, Algebra… =>

\boxed {\text {CT reveals the way how our brain works by analysing, reasoning about structures !}}

Our brain works by:  1) Abstraction 2) Composition 3) Identity (to identify)

What is a Category ? 
1) Abstraction:

  •  Objects
  • Morphism (Arrow)

2) Composition: Associative 
3) Identity

Notes: 

  • Small  Category with “Set” as object. 
  • Large Category without Set as object.
  • Morphism is a Set : “Hom” Set.


Example in Programming
:

  • Object : Types Set
  • Morphism : Function “Sin” converts degree to R: \sin \frac {\pi}{2} = 1

Note: We just look at the Category “Types Set” from external Macroview, “forget ” what it contains, we only know the “composition” (Arrows) between the Category “Type Set”, also “forget” what these Arrows (sin,cosin, tgt, etc) actually are, we only study these arrows’ behavior (Associativity).

2.1 : Function of Set, Morphism of Category

Set: A function is 

  • Surjective (greek: epic / epimorphism 满射),
  • Injective (greek : monic / monomorphism 单射)

Category:  [Surjective]

g 。f = h 。f
=> g = h (Right Cancellation )

2.2 Monomorphism 

f 。g = f 。h
=> g = h
(Left cancellation)

\boxed { \text {Epimorphism + Monomorphism =? Isomorphism }}

NOT Necessary !! Reason ( click here): 

In Haskell, 2 foundation Types: Void, Unit

Void = False
Unit ( ) = True

Functions : absurd, unit
absurd :: Void -> a (a = anything)
unit :: a -> ()

[to be continued 3.1 ….]