How to express {2n+3m+1|n,m∈N} in list comprehension form? (N is the set of natural numbers including 0)

前端 未结 6 1147
北海茫月
北海茫月 2021-01-14 08:12

How do I express {2n+3m+1|n,m∈N} in list comprehension form? N is the set of natural numbers, including 0.

6条回答
  •  天命终不由人
    2021-01-14 08:37

    You can try enumerating all pairs of integers. This code is based in the enumeration described at University of California Berkeley (doesn't include 0)

    data Pair=Pair Int Int deriving Show
    
    instance Enum Pair where
        toEnum n=let l k=truncate (1/2 + sqrt(2.0*fromIntegral k-1))
                     m k=k-(l k-1)*(l k) `div` 2
                 in 
                   Pair (m n) (1+(l n)-(m n))
        fromEnum (Pair x y)=x+((x+y-1)*(x+y-2)) `div` 2
    

    But you can use another enumeration.

    Then you can do:

    [2*n+3*m+1|Pair n m<-map toEnum [1..]]
    

提交回复
热议问题