Haskell中的空间程序 [英] Interspace program in Haskell
问题描述
insert :: Eq(a) => a -> a -> [a] -> [a]
insert m n [] = []
insert m n (x:xs) | m==x = n : x : insert m n xs
| otherwise = x : insert m n xs
m
的所有实例之前将值 n
插入列表中。
The insert
function above is a working function that inserts a value n
into a list before all instances of a value m
.
我需要编写一个 interspace
函数来插入值 n
在列表中的所有值 m
和 q
之间。这是我到目前为止:
I need help writing an interspace
function that inserts a value n
between all values m
and q
in a list. This is what I have so far:
interspace :: Eq(a) => a -> a -> a->[a] -> [a]
interspace m n q[] = []
interspace m n q (x:xs)| m==x && q==(head xs) = n: x : insert m n (headxs)++interspace m n q (xs)
| otherwise = x : interspace m n q xs
推荐答案
要将值添加到列表的前面,您的 insert
函数是不必要的。 (:)
就足够了。就像在 insert
中一样,我们递归地通过列表。既然我们想检查两个值是否匹配,并且会根据是否找到匹配在不同的列表上递归调用函数,最好模式匹配(x1:x2: xs)
而不仅仅是(x:xs)
。
Since you will only be adding values to the front of the list, your insert
function is unnecessary. (:)
will suffice instead. Much like in insert
, we pass recursively over the list. Since we want to check if two values match at a time and will also call the function recursively on different lists based on whether or not we find a match, it's a good idea to pattern match (x1:x2:xs)
rather than just (x:xs)
.
如果 m
匹配 x1
和 q
匹配 x2
,我们将它放在列表的头部,并在列表的其余部分递归调用 interspace
。如果他们不行,我们在(x2:xs)
上调用 interspace
。
If m
matches x1
and q
matches x2
, we place the onto the head of the list and call interspace
recursively on the rest of the list. If they do not mach, we call interspace
on (x2:xs)
.
interspace :: Eq a => a -> a -> a-> [a] -> [a]
interspace m n q [] = []
interspace m n q [x] = [x]
interspace m n q (x1:x2:xs) | m == x1 && q == x2 = m : n : q : interspace m n q xs
| otherwise = x1 : interspace m n q (x2:xs)
用法示例:
ghci>> interspace 1 2 1 [1,1,2,1,1]
[1,2,1,2,1,2,1]
ghci>> interspace 1 2 1 [1,1,3]
[1,2,1,3]
ghci>> interspace 1 2 1 [1,2,4,2]
[1,2,4,2]
ghci>> interspace 1 2 1 [1]
[1]
ghci>> interspace 1 2 1 []
[]
这篇关于Haskell中的空间程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!