首页 > 解决方案 > 替换列表中的元素

问题描述

我对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

标签: haskell

解决方案


您不在列表上进行突变,而是从给定列表创建一个新列表。

一个例子,没有任何错误处理......

> 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]

通过压缩计数来创建一个索引列表,编写一个映射函数来更改所需索引处的值。


推荐阅读