Elixir:生成一个给定参数的n次出现列表(类似于Haskell的重复) [英] Elixir: generate a list of `n` occurrences of a given argument (similar to Haskell's replicate)

查看:184
本文介绍了Elixir:生成一个给定参数的n次出现列表(类似于Haskell的重复)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 Elixir 函数来生成 n 出现一个参数,类似于 Haskell的复制 函数:

$ p $ 输入:replicate 3 5

输出:[c $ c> 5,5,5]

输入:复制5aa

输出:[aa,aa,aa,aa,aa ]

输入:复制5'a'

输出:aaaaa

我做了一个函数来复制一个整数 n 次:

  import字符串

def复制(数字,n)
String.duplicate(to_string(数字),n)
|> split(,trim:true)
|> Enum.map(fn n - > String.to_integer(n)end
end

但是这与规范不符:你能帮我吗?

> def replicate(n,x),do:for _< - 1..n,do:x

如果你想让最后一个case返回字符串,那么你应该使用guard来添加这个类型的定义,如下所示:

  def replicate(n,[x])当is_integer(x),do:to_string(for _<  -  1..n,do:x)$ b $对于_ <1..n,do:x 

iex(1)>重复3,5
[5,5 ,5]
iex(2)>复制品3,'a'
aaa

您也可以使用 String.duplicate / 2 List.duplic ate / 2 ,其他建议:

def replicate(n,x = [ (c),do:String.duplicate(to_string(x),n)
def replicate(n,x),do:List.duplicate(x,n)

另请注意,Char列表'a'和String a不同的东西在Elixir,所以确保你正确理解。



最后,如果这不是一个家庭任务,那么我建议不要重新发明自行车但可能时直接使用String和List模块中的函数。


I want a Elixir function to generate a list of n occurrences of an argument, similar to Haskell's replicate function:

Input: replicate 3 5

Output: [5,5,5]

Input: replicate 5 "aa"

Output: ["aa","aa","aa","aa","aa"]

Input: replicate 5 'a'

Output: "aaaaa"

I have made a function to "replicate" an Integer ntimes:

import String

def replicate(number, n)
  String.duplicate(to_string(number), n) 
  |> split("", trim: true) 
  |> Enum.map(fn n -> String.to_integer(n) end
end

But that's doesn't match the specification :( . Could you help me?

解决方案

def replicate(n, x), do: for _ <- 1..n, do: x

If you want the last case to return string then you should add definition for this type using guard, something like this:

def replicate(n, [x]) when is_integer(x), do: to_string(for _ <- 1..n, do: x)
def replicate(n, x), do: for _ <- 1..n, do: x

iex(1)> replicate 3, 5
[5, 5, 5]
iex(2)> replicate 3, 'a'
"aaa"

You can also use String.duplicate/2 and List.duplicate/2 as other suggested:

def replicate(n, x = [c]) when is_integer(c), do: String.duplicate(to_string(x), n)
def replicate(n, x), do: List.duplicate(x, n)

Also please note that Char list 'a' and String "a" are different things in Elixir, so ensure you understand this correctly.

And finally if this is not a home task then I'd suggest not to reinvent bicycle but directly use functions from String and List module, when possible.

这篇关于Elixir:生成一个给定参数的n次出现列表(类似于Haskell的重复)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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