flatMap()

Functors, Applicatives, and Monads

skybrian 70 days ago

If functional languages had called them the Mappable, Applicable, and FlatMappable interfaces, and used map(), apply(), and flatMap() instead of operators, it would have avoided a lot of confusion.

— Hacker News

bind ~ flatMap

— Me@2015-07-22 06:30:25 PM

2015.09.23 Wednesday ACHK

Monad

Monads in Haskell can be thought of as composable computation descriptions. The essence of monad is thus separation of composition timeline from the composed computation’s execution timeline, as well as the ability of computation to implicitly carry extra data, as pertaining to the computation itself, in addition to its one (hence the name) output, that it will produce when run (or queried, or called upon). This lends monads to supplementing pure calculations with features like I/O, common environment or state, etc.

— Haskell Official Wiki

2015.09.21 Monday ACHK

Folding an infinite list

One big difference is that right folds work on infinite lists, whereas left ones don’t! To put it plainly, if you take an infinite list at some point and you fold it up from the right, you’ll eventually reach the beginning of the list. However, if you take an infinite list at a point and you try to fold it up from the left, you’ll never reach an end!

Learn You a Haskell for Great Good!

Note that the key difference between a left and a right fold is not the order in which the list is traversed, which is always from left to right, but rather how the resulting function applications are nested.

  • With foldr, they are nested on “the inside”

    foldr f y (x:xs) = f x (foldr f y xs)

    Here, the first iteration will result in the outermost application of f. Thus, f has the opportunity to be lazy so that the second argument is either not always evaluated, or it can produce some part of a data structure without forcing its second argument.

  • With foldl, they are nested on “the outside”

    foldl f y (x:xs) = foldl f (f x y) xs

    Here, we can’t evaluate anything until we have reached the outermost application of f, which we will never reach in the case of an infinite list, regardless of whether f is strict or not.

— edited Oct 24 ’11 at 12:21, answered Sep 13 ’11 at 5:17, hammar

— Stack Overflow

2015.08.23 Sunday by ACHK

Exercise One

You Could Have Invented Monads! (And Maybe You Already Have.)

Write the function bind.

——————————

bind f' (gx,gs) = (fx, gs++fs)
                  where
                    (fx,fs) = f' gx

The meaning of bind here:

1. apply f' to the last result data gx, generating the new data fx; and

2. concat the last debug string, gs, to the string generating by f', fs.

— Me@2015.07.19 10:25 PM

2015.07.27 Monday (c) All rights reserved by ACHK

Haskell/Understanding monads/IO, Exercises 2

Haskell

Generalize the bunny invasion example in the list monad chapter for an arbitrary number of generations.

— Wikibooks

——————————

import Control.Monad

generation = replicate 3
gen n = foldr (<=<) return (replicate n generation)

---

["bunny"] >>= gen n

Additional notes:

m >>= g ≡ join (fmap g m)
xs >>= f = concat (map f xs) -- for the List Monad

---

f >=> g
= (\x -> f x) >>= g
= concat (map g (\x -> f x))


---


xs >>= f >=> g
xs >>= (f >=> g)
xs >>= ((\x -> f x) >>= g)
(xs >>= f) >>= g

xs >>= (return >=> g >=> h)
((xs >>= return) >>= g) >>= h


---


xs >>= return
= concat (map f xs)
= concat (map return xs)
= concat (map return ["bunny"])
= concat ([return "bunny"])
= concat ([["bunny"]])
= ["bunny"]


---


-- foldr f acc []     = acc
-- foldr f acc (x:xs) = f x (foldr f acc xs)

-- foldr (<=<) return (replicate n generation)

foldr (<=<) return [h,g]
= (<=<) h (foldr (<=<) return [g])
= (<=<) h ((<=<) g (foldr return []))
= (<=<) h ((<=<) g return)
= h <=< g <=< return


--- 


compose :: [b -> [b]] -> b -> [b]
compose = foldr (<=<) return

foldr (<=<) return (replicate n generation)
= compose (replicate n generation)

— Me@2015-07-08 11:29:40 PM

2015.07.15 Wednesday (c) All rights reserved by ACHK

Things You Should Never Do

It’s important to remember that when you start from scratch there is absolutely no reason to believe that you are going to do a better job than you did the first time. First of all, you probably don’t even have the same programming team that worked on version one, so you don’t actually have “more experience”. You’re just going to make most of the old mistakes again, and introduce some new problems that weren’t in the original version.

— Things You Should Never Do, Part I

— Joel Spolsky

2015.07.12 Sunday ACHK

Euler problem 30

Haskell

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4

As 1 = 1^4 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. 

——————————

sum_5th_powers n = sum $ map ((^5) . digitToInt) (show n)

-- sum_5th_powers 999999 == 354294
-- sum_5th_powers 9999999 == 413343

For a number having more than 6 digits, the fifth powers of its digits cannot be the number itself. So we should consider only numbers with less than 7 digits.

-- sum_5th_powers ______ <= 354294

For the numbers not greater than 354294, the number whose sum_5th_powers can represent the largest number is …

When 2 –> 1, in exchange for 4 –> 9, we earn — we get 354199;
When 4 –> 3, in exchange for 1 –> 9, we earn — we get 353999;
When 5 –> 4, in exchange for 3 –> 9, we earn — we get 349999;
When 3 –> 2, in exchange for 4 –> 9, we earn — we get 299999.

So the maximum number sum_5th_powers can represent is …

-- sum_5th_powers 299999 == 295277

-- 295277
-- 199999

-- sum_5th_powers 199999 == 295246

p30 = [n | n <- [10..m], n == sum_5th_powers n]
    where m = 295246

——————————

— Me@2015-07-06 08:42:07 PM

2015.07.07 Tuesday (c) All rights reserved by ACHK

Euler problem 27.2

p_27 = -(2 * a - 1) * (a ^ 2 - a + 41)
  where
    n = 1000
    m = head $ filter (\x -> x ^ 2 - x + 41 > n) [1 ..]
    a = m - 1

This is the “official” Haskell solution to Euler Problem 27.

This solution is incomprehensible. The following hints are as far as I can get.

Prerequisite Considerations:

  • b must be a prime number, since x^2 + a*x + b must be a prime number when n=0.
  • a = m - 1 is a choice of the prime number b (in x^2 + a*x + b) just(?) smaller than 1000.

When a == 32,

(\x -> x^2 - x + 41) 31 == 971

Why not the prime number 997?

— Me@2015.06.14 08:53 AM

.

It is because 997 is not a prime number generated by the formula x^2 - x + 41.

— Me@2015-06-30 11:07:53 AM

.

The code

l = map (\x -> x^2 - x + 41) [0..40]

is for generating 41 primes with the greatest Euler’s lucky number 41.

— Me@2015.06.14 08:34 AM

λ> :set +s
λ> p_27
[-59231,-61,971]
(0.00 secs, 113,624 bytes)
λ> 

— Me@2025-03-24 01:20:37 PM

.

.

2015.07.01 Wednesday (c) All rights reserved by ACHK

Euler problem 27

primes :: [Int]
primes = 2 : filter (null . tail . primeFactors) [3,5..]

primeFactors :: Int -> [Int]
primeFactors n = factor n primes
  where
    factor n (p : ps)
      | p * p > n = [n]
      | n `mod` p == 0 = p : factor (n `div` p) (p : ps)
      | otherwise = factor n ps

listMax :: Ord a => [a] -> a
listMax (x : xs) = lmf x xs
  where
    lmf x [] = x
    lmf x xs
      | x >= head xs = lmf x (tail xs)
      | otherwise = lmf (head xs) (tail xs)

elemInd :: (Num a, Eq t) => t -> [t] -> a
elemInd y [] = -1
elemInd y (x : xs) = ei 0 y (x : xs)
  where
    ei n y (x : xs)
      | x == y = n
      | null xs = -1
      | otherwise = ei (n + 1) y xs

bList :: [Int]
bList = takeWhile (<= 1000) primes

isPrime :: Int -> Bool
isPrime x | x <= 1    = False
          | otherwise = null $ tail (primeFactors x)

cPrimeLen :: [Int] -> [Int]
cPrimeLen [a, b] = [m, a, b]
    where
      m = length $ takeWhile (isPrime . (\n -> n^2 + a*n + b)) [0..]

p27List :: [[Int]]
p27List = [cPrimeLen [a, b] | a <- [-n..n], b <- bList]
  where
    n = 1000

p27n :: [Int]
p27n = map head p27List

p27 :: [Int]
p27 = p27List !! elemInd (listMax p27n) p27n

λ> :set +s
λ> p27
[71,-61,971]
(2.97 secs, 3,146,880,176 bytes)
λ> 

— Me@2015-06-19 10:01:22 PM

— Me@2025-02-20 04:34:12 PM

.

.

2015.06.20 Saturday (c) All rights reserved by ACHK

Euler problem 26

Haskell

——————————

rems n d xs
    | (r == 0)    = xs ++ [0]
    | (elem r xs) = xs ++ [r] ++ [-1]
    | otherwise   = (rems (10*r) d (xs ++ [r]))
    where r = n `rem` d

remainders n d = rems n d []

recur_cyc (x:xs)
    | (elem 0 ys)          = 0
    | (not (elem (-1) ys)) = -2       
    | (not (elem x xs))    = recur_cyc xs                         
    | otherwise            = (length ys) - 2
    where ys = (x:xs)

elemInd y [] = -1
elemInd y (x:xs) = ei 0 y (x:xs)
                    where
                      ei n y (x:xs)
                          | (x == y)  = n
                          | (null xs) = -1
                          | otherwise = ei (n+1) y xs                                    

list_max [x] = x
list_max (x:xs) = max x $ list_max xs

recur_list = map (\x -> (recur_cyc (remainders 1 x))) [1..1000]

p26 = 1 + (elemInd (list_max recur_list) recur_list)

-- 983

——————————

— Me@2015-06-05 03:25:44 PM

2015.06.05 Friday (c) All rights reserved by ACHK

Euler problem 24

Haskell

------------------------------

deleteNth n xs | n>0 = take (n-1) xs ++ drop n xs

removeItem x xs = filter (/= x) xs

sub_lexico x [] = [[]]

sub_lexico x xs = map (x:) (lexico (removeItem x xs))

merge_sub_lexico [] = []

merge_sub_lexico (x:xs) = x ++ (merge_sub_lexico xs)

lexico [] = [[]]

lexico xs = (merge_sub_lexico (map (\x -> (sub_lexico x xs)) xs))

p24 = (lexico [0,1,2,3,4,5,6,7,8,9]) !! (1000000 - 1)

------------------------------

— Me@2015-05-27 12:09:33 PM

2015.05.27 Wednesday (c) All rights reserved by ACHK

Replay

stephengillie 64 days ago

In gaming, the concept is called a “replay”, where instead of recording the pixels on the screen in every frame, they instead record all inputs processed on every frame, and just replay them thru the same engine. The action is technically idempotent in the game world.

Where this breaks down is when features get updated between revisions. If your game patched the “jump” function to increase upward momentum from 1.1 m/s to 1.13 m/s, the Replay would be incorrect. You would be jumping onto platforms you couldn’t get up to before, moving faster, maybe even dodging enemy attacks that hit you when you played that match.

The human neuroprocessor is always changing and growing, always revising itself. Thus memories replay incorrectly. You apply old feelings to new mental patterns, and sometimes they lead to weird places. Or sometimes you mistake something easy for being difficult, because your memory data is out-of-date for your current processes. 

— Hacker News

2015.04.16 Thursday ACHK

Learn Physics by Programming in Haskell

Learning functional programming and partially applying functions to other functions and such helped me understand tensors a lot better, since that’s basically what contraction is doing. It’s nice to see that the approach can be taken further.

— Snuggly_Person

I also think Haskell and some similar languages (especially Idris) have a great conceptual synergy with physics.

In physics too we strive to express things in ways that strip out extraneous details as much as possible. Haskell really embraces this concept in the sense that you write functions essentially by writing equations. You don’t describe all the mechanical steps to produce an output, you just write down the ‘invariant content’ of the function.

— BlackBrane

2015.03.29 Sunday ACHK

Market price 2

Joel Spolsky

.

Livingston: If people have to pay more, they take the product more seriously?

Spolsky: Definitely. There was a five-user license that was like $199, and that just feels like shareware, practically. But today, when you say that a ten-user license is $999, it starts to feel like a more substantial product. In that market, it still is actually a good deal. But you really have to have a price point that conveys what you think the product positioning should be. Many people will judge where your product fits in the market based on its price.

— Joel Spolsky, Cofounder, Fog Creek Software

.

.

.

2010.11.23 Tuesday ACHK

Cartesian Dualism 2

Transcend duality and non-duality

Duality is correct, in the sense that mind (software) and matter (hardware) are independent.

They are independent in the sense that a piece of software inside a computer (hardware) can be transferred or copied onto another computer. It can continue to exist even after that particular computer ceases to. 

Non-duality is correct, in the sense that mind (software) is pattern of matter (hardware).

They are not two “things”. They are two aspects of the same “thing”.

— Me@2014-10-04 11:57:06 AM

2014.11.07 Friday (c) All rights reserved by ACHK

Cartesian Dualism

In philosophy of mind, dualism is the position that mental phenomena are, in some respects, non-physical, or that the mind and body are not identical. Thus, it encompasses a set of views about the relationship between mind and matter, and is contrasted with other positions, such as physicalism, in the mind–body problem.

— Wikipedia on Dualism (philosophy of mind)

The mind–body problem in philosophy examines the relationship between mind and matter, and in particular the relationship between consciousness and the brain.

The problem was famously addressed by Rene Descartes in the 17th century, resulting in Cartesian dualism, and by pre-Aristotelian philosophers, in Avicennian philosophy, and in earlier Asian traditions. A variety of approaches have been proposed. Most are either dualist or monist. Dualism maintains a rigid distinction between the realms of mind and matter. Monism maintains that there is only one unifying reality, substance or essence in terms of which everything can be explained.

— Wikipedia on Mind–body problem

2014.10.10 Friday ACHK