【问题标题】:Haskell Couldn't match type ‘String -> [Int]’ with ‘[a0]’Haskell 无法将类型“String -> [Int]”与“[a0]”匹配
【发布时间】:2017-11-17 20:08:52
【问题描述】:

我想创建一个程序计算列表中所有元素的出现次数并返回最大序列。我的输入部分有问题。

输入由几个测试用例组成。每个测试用例都以包含两个整数 n 和 q (1 ≤ n, q ≤ 100000) 的行开始。下一行包含 n 个整数 a1 , ... , an (-100000 ≤ ai ≤ 100000

我希望 readNQ 将 n 和 q 作为 [int] 然后传递给 readArray,它将读取 n 元素并分配给 [int],如下所示

module Main where

import Text.Printf
import Data.List

main :: IO()
main = interact (showResults . maxSeqLength . readArray. readNQ)

readNQ :: String -> [Int]
readNQ =  take 2 . (map read) . words

readArray :: [Int] -> String -> [Int]
readArray (n:xs) = take n . (map read) . words


showResults ::  Int -> String
showResults x = printf "\n %d" x

maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs

但是,有一个错误。

frequent.hs:13:47: 错误:

• Couldn't match type ‘String -> [Int]’ with ‘[a0]’
  Expected type: String -> [a0]
    Actual type: String -> String -> [Int]
• Probable cause: ‘(.)’ is applied to too few arguments
  In the second argument of ‘(.)’, namely ‘readArray . readNQ’
  In the second argument of ‘(.)’, namely
    ‘maxSeqLength . readArray . readNQ’
  In the first argument of ‘interact’, namely
    ‘(showResults . maxSeqLength . readArray . readNQ)’

readNQ 和 readArray 的类型有什么问题?

【问题讨论】:

    标签: haskell types


    【解决方案1】:

    那是因为你在函数 readArray :: [Int] -> String -> [Int] 中有一个类型错误,如果你想让这个表达式起作用,它应该有 readArray :: [Int] -> String 类型:

    (showResults . maxSeqLength . readArray . readNQ)
    

    【讨论】:

      【解决方案2】:
      readArray :: [Int] -> String -> [Int]
      

      这需要一个[Int] 并返回一个函数String -> [Int]

      maxSeqLength :: Eq a => [a] -> Int
      

      这接受[a] 列表并返回Int

      由于函数String -> [Int] 不是列表[a],因此您不能使用(.) 组合它们。


      除了错误,还要注意

      readNQ =  take 2 . (map read) . words
      

      从输入中读取前两个整数,并丢弃其余的。没了。函数链中的下一个函数(... . fun . readNQ) 无法访问从第一个函数中丢弃的内容。

      如果你想让下一个函数使用它,你需要修改你的 readNQ 以便它返回一对 ([n1,n2], restOfTheInput)

      可能代码会变得过于复杂而无法以无点风格表达,但没关系。此外,interact 很快开始无法用于大型任务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        • 2014-08-30
        • 1970-01-01
        • 1970-01-01
        • 2016-03-02
        • 2012-09-14
        • 1970-01-01
        相关资源
        最近更新 更多