尝试改进haskell中处理列表的当前丑陋的一段代码 [英] Trying to improve a current ugly piece of code in haskell dealing with lists
问题描述
我试图在Haskell中实现一个函数,该函数将采用任意整数列表 xs
和一个整数 k
,并在所有可能的位置返回一组列表 k
。例如,对于 xs = [0,1]
和 k = 2
,我们会有
myFunction [0,1] 2 = [[2,0,1],[0,2,1],[0,1,2]]
我将它实现为
putOn xs xi =(take i xs)++(x:(drop i xs))
putOnAll xs x = map(putOn xs x)[0 ..(length xs)]
但是,我觉得必须有其他更聪明的方法才能达到同样的效果。我的代码好像有人试图用导弹杀死一个bug。任何人都可以通过这种方式来做出一些巧妙的做法吗?
谢谢
摘自这个问题:
ins x [] = [[x]]
ins x(y:ys)=(x :y:ys):[y:res | res< - ins x ys]
I am trying to implement a function in Haskell that'll take an arbitrary integer list xs
and an integer k
, and returns a set of lists with k
in all possible positions.
For example, for a xs = [0, 1]
and k = 2
, we'd have
myFunction [0, 1] 2 = [ [2, 0, 1], [0, 2, 1], [0, 1, 2] ]
I've implemented it as
putOn xs x i = (take i xs) ++ (x:(drop i xs))
putOnAll xs x = map (putOn xs x) [0..(length xs)]
yet, I feel there must be other smarter ways to achieve the same. My code seems like someone trying to kill a bug with a missile. Could anyone make sugestions on ways to do something clever than this bit of code?
Thanks
Taken from this question:
ins x [] = [[x]]
ins x (y:ys) = (x:y:ys):[ y:res | res <- ins x ys]
这篇关于尝试改进haskell中处理列表的当前丑陋的一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!