haskell - 替换列表中的元素
问题描述
我对haskell中的列表有一个简单的问题。(我是haskell的初学者)
我会知道如何替换数组中的元素,但要尽可能简单。
[1, 2, 4, 4, 5]
至
[1, 2, 3, 4, 5]
还有我怎么能在列表中出现一个数字
[1, 2, 3, 4]
至
[1, 2, 3, 4, 5]
我已经阅读了该教程: http: //learnyouahaskell.com/starting-out
我正在考虑第一个问题:
array = [1, 2, 4, 4, 5]
array[2] = 2
第二个:
array = [1, 2, 3, 4]
array ++ [5]
Ps:array ++ [5]
与 ghci 一起工作,但是当我在代码中这样做时:
array = [1, 2, 3, 4]
modifyarray = do
print $ array !! 2
array ++ [5]
print $ array !! 4
那行不通...
编辑 :
module Main where
import Lib
import System.Environment
import System.Exit
redPoint = [3,4,2]
fillArray file x = do
let line = lines file
print $ line
replaceAt x y = map (\(i,v) -> if (i==x) then y else v) . zip [1..]
replaceArray = do
print $ redPoint !! 2
replaceAt 2 9 redPoint
print $ redPoint !! 2
openfile a n path = do
file <- readFile path
fillArray file 0
replaceArray
exit = exitWith ExitSuccess
error_exit = exitWith (ExitFailure 84)
parse [a, n, path] = openfile a n path >> exit
parse [] = error_exit
main = do
getArgs >>= parse
这个错误:
无法将类型“[]”与“IO”匹配 预期类型:IO Integer 实际类型:[Integer] • 在“do”块的结构中:replaceAt 2 9 redPoint 在表达式中:do print $ redPoint !! 2 replaceAt 2 9 redPoint print $ redPoint !! 2 在“replaceArray”的等式中:replaceArray = do print $ redPoint !! 2 replaceAt 2 9 redPoint print $ redPoint !! 2
解决方案
您不在列表上进行突变,而是从给定列表创建一个新列表。
一个例子,没有任何错误处理......
> replaceAt x y = map (\(i,v) -> if (i==x) then y else v) . zip [1..]
> replaceAt 3 10 [1..5]
[1,2,10,4,5]
通过压缩计数来创建一个索引列表,编写一个映射函数来更改所需索引处的值。
推荐阅读
- javascript - How to run some code before page is displayed
- bash - grep 多个文件中的多个字符串,并在找到第一个匹配项时停止处理其他文件
- c# - 嵌套的 if 条件与多个单独的 if 条件,每个条件都有 return 语句
- mysql - 您如何记录使用 SQL 访问数据库的程序?
- gcc - 实在看不懂gcc怎么初始化数组
- c# - 文件打开 dotnet core 2.1 System.IO.IOException
- android - 我越来越未定义不是一个对象(评估'this.props.navigation.navigate')
- python - inspect.signature 究竟如何与类一起工作?
- pentaho - 我可以从 pentaho 中的 URL 获取参数吗?
- c# - .NET Console.Readline 不读取输入的第一行