我有一个初学者的 Haskell 问题。
今年我正在使用 Advent of Code 来学习 Haskell。在解决第一个问题时,我需要将字符串转换为整数。
这是我的代码:
import Data.List.Split
import System.IO
main = do
input <- getContents
let bags = splitWhen (=="") $ lines input
let bagsInteger = map (\arr -> map (\x -> read x :: Integer)) bags :: [[Integer]]
let totals = map (sum) bagsInteger
putStrLn $ show $ maximum totals
当我运行
ghc
时,会得到以下结果。azl@Alains-MacBook-Air aoc-2022 % ghc 1.hs
Loaded package environment from /Users/azl/.ghc/aarch64-darwin-9.2.5/environments/default
[1 of 1] Compiling Main ( 1.hs, 1.o )
1.hs:7:36: error:
• Couldn't match expected type: [Integer]
with actual type: [String] -> [Integer]
• Probable cause: ‘map’ is applied to too few arguments
In the expression: map (\ x -> read x :: Integer)
In the first argument of ‘map’, namely
‘(\ arr -> map (\ x -> read x :: Integer))’
In the expression:
map (\ arr -> map (\ x -> read x :: Integer)) bags :: [[Integer]]
|
7 | let bagsInteger = map (\arr -> map (\x -> read x :: Integer)) bags :: [[Integer]]
非常感谢您提供的帮助!
map (sum) list
最好写成map sum list
。2)函数\arg -> f arg
和f
是一样的。因此,map (\arr -> map (\x->read x::Integer) arr) bags
等同于map (map (\x->read x::Integer)) bags
。3)putStrLn $ show $ ...
很常见,可以缩写为print $ ...
。4)建议你使用-Wall
标志打开警告,因为它可以捕获几个初学者错误。祝你 Haskell 学习愉快! - chiinteract
,使得这个程序非常简洁:interact (show . maximum . map (sum . map read) . splitWhen null . lines)
。(这使用了默认规则来选择Integer
作为read
的类型,但如果您想包含明确的类型签名也是合理的。) - Daniel Wagner