Haskell 文件读取和查找值

Haskell file reading and finding values

我最近开始学习 Haskell,但我很难弄清楚如何解释文本文件。

我有以下 .txt 文件:

ncols         5
nrows         5
xllcorner     809970
yllcorner     169790
cellsize      20
NODATA_value  -9999
9 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 2 0 0 3

前 6 行仅显示我在 GIS 软件中处理文件时需要的一些信息。当我尝试使用 Haskell.

中的以下数字时,真正的交易开始了

我想告诉 Haskell 查找数字 9、1、2 和 3 的位置,并打印出这些数字实际所在的行和列的编号。在这种情况下 Haskell 应该打印:

The value 9 is in row 1 and column 1
The value 1 is in row 2 and column 2
The value 2 is in row 5 and column 2
The value 3 is in row 5 and column 5

我尝试在教程和其他 Haskell 脚本中找到解决方案(或至少类似的解释文件的方法)但没有成功,因此非常感谢任何帮助。

这是一个脚本示例,可以执行您想要的操作。请注意,这将以其当前形式不会优雅地失败(但鉴于这是一个脚本,我怀疑这是一个问题)。确保文件末尾有一个尾随换行符!

import Control.Monad (replicateM, when)
import Data.Traversable (for)
import System.Environment (getArgs)

main = do

  -- numbers we are looking for
  numbers <- getArgs 

  -- get the key-value metadata
  metadata <- replicateM 6 $ do
    [key,value] <- words <$> getLine
    return (key,value)

  let Just rows = read <$> lookup "nrows" metadata
      Just cols = read <$> lookup "ncols" metadata

  -- loop over all the entries
  for [1..rows] $ \row ->do
    rawRow <- words <$> getLine
    for (zip [1..cols] rawRow) $ \(col,cell) ->
      when (cell `elem` numbers)
        (putStrLn ("The value " ++ cell ++ " is in row " ++ show row ++ " and column " ++ show col))

要使用它,请将其作为命令行参数传递给您要查找的数字,然后将其作为数据文件的输入。

$ ghc script.hs
$ ./script 9 1 2 3 < data.txt

如果您有任何问题,请告诉我!


我不太确定你是想查找一组固定的数字,还是任何非零数字。正如你问的前者问题,我就是这么做的。