Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of a list comprehension

I'm just getting started with Haskell and finished a nice exercise to make a Caesar cipher.

One of the first steps was to make a function that will take a letter and turn it into a number. I know that chr and ord can do this already but part of the exercise was to write your own.

let2num c = head [ b | (a,b) <- zip ['a'..'z'] [0..25], a==c]

I'm new to the Haskell syntax and one of the first things I learned was list comprehensions, so that has become my hammer. I'm very curious though, what is another (likely better) way to write this function?

If you're curious the rest of the cipher is in a gist.

EDIT

I'm also interested in other ways to translate back from numbers to letters.

num2let d = head [ a | (a,b) <- zip ['a'..'z'] [0..25], b==(d `mod` 26)]
like image 684
lashleigh Avatar asked Jan 26 '11 08:01

lashleigh


People also ask

What is faster than list comprehension?

For loops are faster than list comprehensions to run functions.

Which is better list comprehension or map?

List comprehension is more concise and easier to read as compared to map. List comprehension are used when a list of results is required as map only returns a map object and does not return any list. Map is faster in case of calling an already defined function (as no lambda is required).

Are list comprehensions necessary?

List comprehensions are useful and can help you write elegant code that's easy to read and debug, but they're not the right choice for all circumstances. They might make your code run more slowly or use more memory.

Is map more efficient than list comprehension?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.


1 Answers

My solution:

import Data.List
let2num c = let (Just n) = elemIndex c ['a'..'z'] in n

Or:

import Data.List
import Data.Maybe
let2num c = fromJust $ elemIndex c ['a'..'z']

Or in pointless style:

import Data.List
import Data.Maybe
let2num = fromJust . (flip elemIndex) ['a'..'z']

The function elemIndex returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element.

The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), or it is empty (represented as Nothing). Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error.

The function fromJust extracts the element out of a Just.

like image 115
YasirA Avatar answered Nov 15 '22 10:11

YasirA