如何在Elixir中替换数组中的元素 [英] How to replace elements in an array in elixir

查看:32
本文介绍了如何在Elixir中替换数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用3替换所有出现的2.我想这样做而不使用索引的值,因为那将是硬编码.到目前为止,我有:

I want to replace all occurrences of 2 with 3.I want to do this without using the value of the index because that would be hardcoding. What I have so far is:


list=[1,2,3,4,2,34,2]

replace_at(list, index, value)

Enum.each list, fn(x) ->
if x==2 do
  replace_at(list, index, 3)
end

Enum.each list, fn(x) ->
IO.puts x
end

推荐答案

在Elixir中,您没有数组,但是地图 Enum 模块的

In Elixir, you do not have arrays, but linked list. If you simply want to replace all ocurrences of 2 with 3, you can use the map function, of the Enum module like this:

iex(1)> Enum.map(list, fn x -> if x == 2, do: 3, else: x end)
[1, 3, 3, 4, 3, 34, 3]

您还可以使用模式匹配:

You could also use pattern matching:

iex(1)> Enum.map(list, fn
...(1)> 2 -> 3
...(1)> x -> x
...(1)> end)

这篇关于如何在Elixir中替换数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆