简体   繁体   中英

Take - Haskell problems within lists

I am in the process of learning Haskell. I have a function that looks as follows:

takeN :: Integral a => a -> [a]
takeN n = take n [x | x<-[0..]]

All I want this to do, is return n amount of elements in an infinite list, and I am unaware of why this is not working. Any explanations of how to fix it without abandoning my binding (?)

The reason this doesn't work is that take has the type Int -> [a] -> [a] . The number must be an Int , and can't be any Integral .

You can address the issue with fromIntegral :

takeN :: Integral a => a -> [a]
takeN n = take (fromIntegral n) [x | x<-[0..]]

您可以在不使用自己的功能的情况下执行此操作:输入>>取3 [1 ..]输出>> [1,2,3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM