Point free notation, recursion, and pattern matching

So, I listen a lot about access control programming all the time, and I decided to do a little experiment to test my understanding. This included a pointed function for calculating the factorial of a number and converting it to point form. I managed to do this, but a point-free result is much less readable than the specified result.

-- pointed fact 0 = 1 fact n = n * (fact (n-1)) -- point free fact' = foldr1 (*) . takeWhile ((<) 0) . iterate (flip (-) 1) 

Am I missing something substantial to indicate a free notation, or is it readable, like some conversions? It seems to me that most of the fact function is the pattern matching to zero, and indeed, pattern matching is one of the biggest reasons I love Haskell. Be that as it may, a dotted sequence note apparently completely prohibits this, along with some other things that are extremely useful as an understanding of lists.

+7
source share
2 answers

The canonical factorial in free form is equal to:

 fact = product . enumFromTo 1 

(which is equivalent to fact n = product [1..n] )

I find this pretty readable. However, I agree that the original version:

 fact 0 = 1 fact n = n * (fact (n-1)) 

It meets the definition very well and is also readable.

The point (ha!) Of dimensionless form is to facilitate the discussion of functions as the composition of other functions. However, the factorial function is not really an excellent candidate for this kind of reasoning.

Your decision is obvious.

+15
source

For each data type of an algebraic union, there must be a discrimination function of the case type, which encapsulates the pattern matching for this type. We already have

 either :: (a -> c) -> (b -> c) -> Either ab -> c maybe :: b -> (a -> b) -> Maybe a -> b 

Similarly, there should be such a function for numbers,

 num :: (Num a) => b -> (a -> b) -> a -> b num z nz 0 = z num z nz x = nz x 

so we can write

 import Control.Applicative import Data.Function fact :: (Num a) => a -> a fact x = num 1 (\x-> (*) (fact (pred x)) x) x = num 1 ((*) =<< (fact.pred)) x 

i.e.

 fact = (num 1 . ((*) =<<) . (. pred)) fact = fix (num 1 . ((*) =<<) . (. pred)) 
+2
source

All Articles