New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Haskell函数式编程入门里的一个小问题 #145

Open
vincenteof opened this Issue Jan 21, 2019 · 1 comment

Comments

Projects
None yet
2 participants
@vincenteof
Copy link

vincenteof commented Jan 21, 2019

书里的练习7.2.4是要求一种遍历[(x, y) | x <- [1 ..], y <- [1 ..]]里所有元组的方法。这个问题跟证明有理数集可数是一样的,我知道如何按照那种方式去生成。

书里的提示貌似跟那种方式不太一样,是这样的:

定义一个类似于 concat 的函数 interLeave,这个函数可以将两个无穷的列表合在一起。使用 interLeave 函数与 foldr 函数定义一个函数 interLeaveLists,它与 concat 功能相似。再使用 interLeaveLists 对 [[(x,y)| y <- [1..]] | x <- [1..]]进行连接

我尝试了一下,大概是这样的:

interLeave :: [a] -> [a] -> [a]
interLeave xs ys = foldr (\(x, y) acc -> x : y : acc) [] (zip xs ys)

interLeaveLists :: [[a]] -> [a]
interLeaveLists = foldr1 interLeave

allResults = interLeaveLists [[(x, y) | y <- [1..]] | x <- [1..]]

结果是无穷递归了,不知道如何按照书里的思路去fix这个问题呢,求教。

@kalxd

This comment has been minimized.

Copy link

kalxd commented Feb 14, 2019

没看过这本书,如代码上来看,foldr一条无穷长的列表自然是无穷递归了。可以试着take一部分出来。

interLeave :: [a] -> [a] -> [a]
interLeave xs ys = foldr (\(x, y) acc -> x : y : acc) [] $ take 10 $ zip xs ys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment