Haskell中将列表的列表转换为单个列表

3

我有一个初学者的 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]]

非常感谢您提供的帮助!


1
由于你在学习,我会给一些意见。1)在Haskell中,单独的名称不需要加括号。因此,map (sum) list最好写成map sum list。2)函数\arg -> f argf是一样的。因此,map (\arr -> map (\x->read x::Integer) arr) bags等同于map (map (\x->read x::Integer)) bags。3)putStrLn $ show $ ...很常见,可以缩写为print $ ...。4)建议你使用-Wall标志打开警告,因为它可以捕获几个初学者错误。祝你 Haskell 学习愉快! - chi
1
对于类Unix标准的stdin-to-stdout程序,还有一个方便的函数interact,使得这个程序非常简洁: interact (show . maximum . map (sum . map read) . splitWhen null . lines)。(这使用了默认规则来选择Integer作为read的类型,但如果您想包含明确的类型签名也是合理的。) - Daniel Wagner
1个回答

3

你忘记了arr

map (\arr -> map (...) arr) bags
--                     ^^^

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接