-2

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]. 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. I have tried using zipWith in adjust as let adjust m = zipWith (mod (almostVig m) 26), but that also failed. How can I apply mod to every element in a list to produce a new list in which no element is greater than 25?

  • 2
    What is `(Char, Int)..(Char, Int)`? What about `[Int] [Int]`? Appreciate that you add signatures, but these don't make sense. Please write an actual Haskell module that typechecks. And don't add stuff that's not relevant to the questions. – leftaroundabout Oct 31 '17 at 15:20
  • Sorry, I'm new to this and self-taught. It was my best guess. – Lillian Wangler Oct 31 '17 at 15:58

2 Answers2

4

You can use map:

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.

`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.

lisyarus
  • 15,025
  • 3
  • 43
  • 68
2

Use list comprehension.

[x `mod` 26 | x <- almostVig]

This will result in a new list in which all elements will be less than 26.

babon
  • 3,615
  • 2
  • 20
  • 20