我的作业有问题,我必须编写一个程序,它的行为类似于wc
. 我目前的方法如下:
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as UTF8
numBytesUtf8 :: String -> Int
numBytesUtf8 = BS.length . UTF8.fromString
help = "Wrong number or wrong arguments provided.\n\
\Possible arguments are: [l, w, c, b, ll]\n\n\
\options:\n\
\ -l -> Return line count\n\
\ -w -> Return word count\n\
\ -c -> Return character count\n\
\ -b -> Return byte count\n\
\ -ll -> Return character count of the longest line"
getLongestLine l r
| r == [] = return l
| length next > length l = getLongestLine next rest
| otherwise = getLongestLine l rest
where
next = head r
rest = tail r
getLongestLineLength :: [Char] -> a -> Int
getLongestLineLength f = length . words . getLongestLine h t
where
l = lines f
h = head l
t = tail l
handleArgs :: [[Char]] -> [Char] -> IO ()
handleArgs args f
| head args == "-l" = print . length . lines $ f
| head args == "-w" = print . length . words $ f
| head args == "-c" = print . length $ f
| head args == "-b" = print . numBytesUtf8 $ f
| head args == "-ll" = print ( getLongestLineLength f )
| otherwise = putStrLn help
但是目前我收到以下错误:
• No instance for (Show (a0 -> Int)) arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In the expression: print (getLongestLineLength f)
In an equation for ‘handleArgs’:
handleArgs args f
| head args == "-l" = print . length . lines $ f
| head args == "-w" = print . length . words $ f
| head args == "-c" = print . length $ f
| head args == "-b" = print . numBytesUtf8 $ f
| head args == "-ll" = print (getLongestLineLength f)
| otherwise = putStrLn help
|
43 | | head args == "-ll" = print ( getLongestLineLength f )
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我还是这门语言的新手,直到现在才出人意料。但我不知道如何处理a -> Int
,也不知道如何打印。
任何帮助和其他提示都被挪用了:)
getLongestLine l r
| r == [] = return l
....
return
此处注入l
任何 monad,使 的类型getLongestLine
为以下形式
Monad m => something -> something -> m (something)
现在,这是一个事件:您可能不打算这样做。不幸的是,由于您也没有告诉 GHCgetLongestLine
预期的类型是什么,GHC 推断出上面意外的类型并继续前进,导致程序稍后出现问题。使用类型签名时getLongestLine
,您会在此处遇到类型错误。
你很不走运,因为错误return
可能会导致类型错误,但在这种情况下没有。
确实,稍后会选择 monad,(->) a
因为您使用组合
length . words . getLongestLine h t
这导致类型
getLongestLineLength :: [Char] -> a -> Int
有一个额外的不需要的a
参数,并getLongestLineLength
使用两个参数而不是一个参数(第二个参数被传递给getLongestLine
,并在那里被忽略)。
当你最终只通过一个参数时,GHC 终于抱怨了。
该怎么办:
return
除非您正在使用 monad,否则不要使用。使用l
代替return l
。您的代码中还有其他几个问题,您可能需要进行一些重大更改。我建议您尽早使用 将字符串拆分为单词words
,然后将结果传递[String]
给程序的其余部分。不是计算最长的线,然后计算其长度,而是先计算长度,然后取最大值。
longestWordLength :: String -> Int
longestWordLength = maximum . map length . words
与您的问题没有密切关系,但一般建议:
head
, tail
, l==[]
。尽可能使用模式匹配而不是守卫。-Wall
并解决它们。这会将丢失的类型签名报告给getLongestLine
,从而导致误解。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句