Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

haskell - Why is ListT monad transformer considered buggy - what monad laws it breaks?

I've seen mentioned that

ListT is a classic example of a buggy monad transformer that doesn't satisfy the monad laws.

Can this be demonstrated by a simple example?

Edit: My idea with ListT [] is a bit wrong, I missed that the documentation requires the inner monad to be commutative. So, is ListT buggy just in the sense that has this requirement, or is there another problem? (The examples at Haskell wiki all use ListT IO and IO is obviously not commutative.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simple example that shows how it fails the associativity law:

v :: Int -> ListT [] Int
v 0 = ListT [[0, 1]]
v 1 = ListT [[0], [1]]

main = do
    print $ runListT $ ((v >=> v) >=> v) 0
    -- = [[0,1,0,0,1],[0,1,1,0,1],[0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1]]
    print $ runListT $ (v >=> (v >=> v)) 0
    -- = [[0,1,0,0,1],[0,1,0,0],[0,1,0,1],[0,1,1,0,1],[0,1,1,0],[0,1,1,1]]

More examples (mostly using IO) and a solution how to fix ListT can be found at ListT done right.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...