Does haskell keep track of the composition of a function?

I was wondering if Haskell tracks the weather, a function is a functional composition, is it possible for me to define a function that does something similar to this?

compositionSplit fg = (f,g) 
+7
source share
2 answers

No, that would be impossible.

For example,

 f1 = (+ 1) . (+ 1) :: Int -> Int 

is the same function as

 f2 = subtract 1 . (+ 3) :: Int -> Int 

and referential transparency requires that equals can be replaced by equals, so if compositionSplit were possible, then

  • you need to create the same result for f1 and f2 , since this is the same function, but
  • compositionSplit f1 = ((+ 1), (+1)) and compositionSplit f2 = (subtract 1, (+ 3)) will be required by the compositionSplit specification.
+18
source

Can. In a strictly interpreting uncompiled implementation, you can represent functions as

 data Function = F Source | Compo Function Function 

and then you just define

 compositionSplit (Compo fg) = Just (f,g) compositionSplit _ = Nothing 

Such an implementation will consider the equality of functions (according to relational transparency) as intensional , not extensional . Since the language itself does not say anything about the equality of the functions of AFAIK, this should not affect anything (except, perhaps, performance).

In compiled implementations, this can also be achieved, for example. keeping the origin for each object in memory.


AndrewC gives a winning counter argument: for two values a=f.(gh) and b=(fg).h , if we want to consider them equal values, which we usually do, in Haskell - fst.unJust.deCompo will produce two different result, violation of link transparency. Therefore, it cannot be part of the pure FP paradigm. He would have to return what we could legitimately consider equal values ​​in two cases, and we could not disassemble it without violating purity. Perhaps such a thing may exist in some unclean monad, but this is not what the OP asked for, unfortunately. :) So, this answer is erroneous.

+4
source

All Articles