create_subseq size xs =
if (length xs) == size
then [ [ x | x <- s] | s <- xs]
else [ [ i | i <- subxs] | subxs <- (take size xs)] ++ create_subseq size (tail xs)
我一直在尝试使用下面的行在ghci中运行此代码但是我得到下面的错误
create_subseq 3 [1,2,3,4]
No instance for (Num [t0]) arising from the literal `1'
Possible fix: add an instance declaration for (Num [t0])
In the expression: 1
In the second argument of `create_subseq', namely `[1, 2, 3, 4]'
In the expression: create_subseq 3 [1, 2, 3, 4]
答案 0 :(得分:4)
如果您查看create_subseq
中ghci
的类型,就会明白这一点:
*Main> :t create_subseq
create_subseq :: Int -> [[t]] -> [[t]]
换句话说,第二个参数应该是某个列表的列表,但是您只传递了一个数字列表。 ghci
然后尝试将数字解释为列表,但它不能,因此错误消息。
如果您想知道为什么create_subseq
会列出一系列列表,请查看您编写的列表推导。他们每个人都假设原始参数xs
是一个列表,当你查看列表xs
中的一个元素时,你有另一个列表,你可以写一个嵌套列表理解。
答案 1 :(得分:0)
这是我的代码,我开始弄清楚haskell。到目前为止我喜欢它,我希望继续学习。
-- Program will read a file with a 1000 digit number. The goal of the program
-- is to find a sequence within that number that is 13 digits long and has
-- the largest product. This program is not safe to run on 32 bit machines
-- you will run into number overflow and get inaccurate results
import System.Environment
import Data.Char
create_sub_seq :: Int->[Int]->[[Int]]
create_sub_seq n xs = if length xs == n
then [xs]
else [[i | i <- take n xs]]++create_sub_seq n (tail xs)
prod :: [Int]->Int
prod xs = foldl (*) 1 xs
getIntArray :: [Char] -> [Int]
getIntArray xs = [digitToInt i |i <- xs, not(i=='\n')]
max_sub_seq :: ([Int]->Int)->[[Int]]->[Int]
max_sub_seq f [] = []
max_sub_seq f (xs:xxs) = if (f b) > (f xs)
then b
else xs
where b=max_sub_seq f xxs
main = do [f] <- getArgs
s <- readFile f
-- print( create_sub_seq 4 (getIntArray s))
print( max_sub_seq prod (create_sub_seq 13 (getIntArray s)) )
print( prod ( max_sub_seq prod (create_sub_seq 13 (getIntArray s)) ) )