无限计数器的无限列表

无限计数器的无限列表

本文介绍了无限计数器的无限列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于那些心存疑虑的人来说,这不是家庭作业,只是好奇而已。

给定一个有限的字母表,是否可以构建一个无限长的单词列表字母顺序反向的字典顺序?



即,给定字母表ab



是否可以构造列表:

  [aaaaaa ...,baaaaa ...,abaaaa ...,bbaaaa ...,aabaaa ... ,...] 

其中 ...

一个天真的尝试是:

 计数器字母表= [c:ounter | ounter<  -  counter alphabet,c<  -  alphabet] 

但这不起作用,因为它是递归的。



当然,使用工作版本时,如果您尝试打印结果,则只会看到第一个元素被打印为无限列表字母表中的第一个元素。但是,您应该可以这样做:

  mapM_(print。take 2)。拿4。计数器$ab

并查看输出:

  aa 
ba
ab
bb


解决方案

为什么不能修复它?

  ghci的>让bar = let foo〜(st:sts)= [c:st | c<  - ab] ++ foo sts in fix foo 
ghci>拿5。地图(带5)$ bar
[aaaaa,baaaa,abaaa,bbaaa,aabaa]
取10。 map(take 5)$ bar
[aaaaa,baaaa,abaaa,bbaaa,aabaa,babaa,abbaa,bbbaa,aaaba,baaba ]


For those with suspicious minds, this is not homework, just curious.

Given a finite alphabet, is it possible to construct a list of infinitely long words made from the alphabet in reverse lexographic order?

i.e. given the alphabet "ab"

is it possible to construct the list:

["aaaaaa...", "baaaaa...", "abaaaa...", "bbaaaa...", "aabaaa...", ...]

where ... represents the list (and list of lists) extending to infinite length.

A naïve attempt is:

counters alphabet = [c:ounter | ounter <- counters alphabet, c <- alphabet]

but this doesn't work since it is left recursive.

Of course, with a working version, if you tried to print the result, you would only see the first element being printed as an infinite list of the first element from the alphabet. However, you should be able to do this:

mapM_ (print . take 2) . take 4 . counters $ "ab"

and see the output:

aa
ba
ab
bb
解决方案

Why not fix it?

ghci> let bar = let foo ~(st:sts) = [c:st | c <- "ab"] ++ foo sts in fix foo
ghci> take 5 . map (take 5) $ bar
["aaaaa","baaaa","abaaa","bbaaa","aabaa"]
take 10 . map (take 5) $ bar
["aaaaa","baaaa","abaaa","bbaaa","aabaa","babaa","abbaa","bbbaa","aaaba","baaba"]

这篇关于无限计数器的无限列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:24