我正在尝试学习Haskell,但我无法找到解决以下问题的方法。
考虑以下类型为ourFunction :: [[String]] -> [[String]]
的函数
当两个伴随字符串相同时,它们应更改为'x'
。
示例:
ourFunction[["a","b","c","d"],[["e","f","a","d"]
a
b
c
d
e
f
a
d
它应该返回[["a","b","c","x"],[["e","f","a","x"]
。
我要求它理解列表索引并更改函数列表中的值。
答案 0 :(得分:0)
假设
中的列表相同import Data.List
test = replaceWithxForEqualIndexes [["a","b","c","d"],["e","f","a","d"]]
--Here is the magic, transpose so you get same indexes in the same list,
--then check for equality and replace if equals, then transpose back
replaceWithxForEqualIndexes x = transpose $ map ifSameChangeToX $ transpose x
ifSameChangeToX x = ifSameChangeTo x "x"
ifSameChangeTo :: (Eq a) => [a] -> a -> [a]
ifSameChangeTo x rep
| allTheSame x = take (length x) (repeat rep)
| otherwise = x
allTheSame :: (Eq a) => [a] -> Bool
allTheSame xs = and $ map (== head xs) (tail xs)
答案 1 :(得分:0)
import Data.List
ourFunction :: [[String]] -> [[String]]
ourFunction input = [fst result, snd result]
where result = unzip $ zipWith (\x y -> if x == y then ("x", "x") else (x, y)) (head input) (last input)