2015-05-15 123 views
0

我完全失去了为什么下面不工作:为什么(字符串,诠释)预期而不是(字符,诠释)?

takeRange :: Int -> (a,Int) -> [(a,Int)] -> [(a,Int)] 
takeRange n elem list = dropWhile (\x -> snd x < snd elem) (takeWhile (\x -> snd x < (snd elem) + n) list) 

seriesLargestProd :: String -> Int -> Int 
seriesLargestProd "" _ = 0 
seriesLargestProd _ 0 = 0 
seriesLargestProd s n = maximum [foldl1 (*) $ map (read . fst) (takeRange n pair zipped) 
           | pair <- zipped, snd pair <= lastStartingIndex] 
            where zipped = zip s [1..] 
              lastStartingIndex = (length s) - (n-1) 

错误消息我得到:

Couldn't match type `Char' with `[Char]' 
    Expected type: (String, Int) 
     Actual type: (Char, Int) 
    In the second argument of `takeRange', namely `pair' 
    In the second argument of `map', namely `(takeRange n pair zipped)' 

Couldn't match type `Char' with `[Char]' 
    Expected type: [(String, Int)] 
     Actual type: [(Char, Int)] 
    In the third argument of `takeRange', namely `zipped' 
    In the second argument of `map', namely `(takeRange n pair zipped)' 

如果任何人的兴趣,这应该是一个答案问题8的Project Euler

回答

3

您映射的函数read . fst的类型为Read a => (String, b) -> a。所以map (read . fst) :: Read a => [(String, b)] -> [a]。但zipped的类型为[(Char, Int)],并且takeRange返回与其输入相同类型的列表。

顺便说一句,你可以实现takeRange作为

takeRange n elem list = take n $ drop (snd elem) $ list 

你通过手动计数的指标做额外的工作,并作为@ sepp2k提到这将是更地道与元组模式匹配。

+0

谢谢你的回答。这真的很有帮助。 – Kapol

2

为什么一个字符串是预期的,当压缩将明显“分裂”字符串成个别字符?

因为read需要一个字符串。为了将一个数字转换为一个整数,使用digitToInt而不是read(或者,您也可以使用read [theChar]创建一个单字符字符串并将其转换,但由于存在digitToInt,因此不需要这样做)。

PS:代替snd xsnd pair,使用模式匹配来单独指定对的元素会更加通俗。

+0

我已经删除了引用的部分。对不起。 – Kapol

相关问题