[英]How to apply mod to every element in a list in Haskell
I have a function that produces list of integers to which I would like to apply mod so that no element in the list is greater than 25. For example, the list [6,8,18,28,14,25] should return as [6,8,18,2,14,25].我有一个生成整数列表的函数,我想对其应用 mod,以便列表中的任何元素都不大于 25。例如,列表 [6,8,18,28,14,25] 应返回为[6,8,18,2,14,25]。 The code so far is as follows.
到目前为止的代码如下。
let charIntList = zip ['a'..'z'] [0..25]
let getIntFromList (x:xs) a = if fst x == a then snd x else getIntFromList xs a
charToInt :: Char -> Int
let charToInt a = getIntFromList charIntList a
zipWithPosition :: [Char] -> [(Char, Int)]
let zipWithPosition m = zip m [0..length m]
position :: [(Char, Int)] -> [Int]
let position m = map snd (zipWithPosition m)
messToInt :: [Char] -> [Int]
let messToInt m = map charToInt m
almostVig :: [Int] [Int] -> [Int]
let almostVig m = zipWith (+) (messToInt m) (position m)
adjust :: [Int] -> [Int]
let adjust m = (mod (almostVig m) 26)
This code fails to apply mod to every element in the list generated by almostVig.此代码无法将 mod 应用于由几乎Vig 生成的列表中的每个元素。 I have tried using zipWith in
adjust
as let adjust m = zipWith (mod (almostVig m) 26)
, but that also failed.我试过在
adjust
使用 zipWith as let adjust m = zipWith (mod (almostVig m) 26)
,但也失败了。 How can I apply mod
to every element in a list to produce a new list in which no element is greater than 25?如何将
mod
应用于列表中的每个元素以生成一个新列表,其中没有元素大于 25?
let adjust m = map (`mod` 26) (almostVig m)
map
has type (a -> b) -> [a] -> [b]
: it takes a function and applies it to a list element-wise. map
具有类型(a -> b) -> [a] -> [b]
:它接受一个函数并将其应用于列表元素。
`mod` 26
is partial function application: it turns the function mod
to an operator `mod`
so that it can be used inline, like 128 `mod` 26
instead of mod 128 26
, and then partially applies the second argument. `mod` 26
是部分函数应用:它将函数mod
转换为运算符`mod`
以便可以内联使用,例如128 `mod` 26
而不是mod 128 26
,然后部分应用第二个参数。
Use list comprehension.使用列表理解。
[x `mod` 26 | x <- almostVig]
This will result in a new list in which all elements will be less than 26
.这将产生一个新列表,其中所有元素都将小于
26
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.