Skip to content

Instantly share code, notes, and snippets.

@jdeisenberg
Last active August 14, 2017 13:21
Show Gist options
  • Select an option

  • Save jdeisenberg/866b0902206045a1b9a90b184c3822cb to your computer and use it in GitHub Desktop.

Select an option

Save jdeisenberg/866b0902206045a1b9a90b184c3822cb to your computer and use it in GitHub Desktop.
Description of a problem to solve in Haskell

Here's the problem at hand: I have a file with some data like this:

   Name;email;zip;status
   Joe Doakes;[email protected];07123;A
   Nancy Smith;[email protected];98146;I
   Armando Gonzales;[email protected];77194;A

I want to semi-anonymize it by changing all the email addresses to end in @example.com and replacing the ZIP code with a random 5-digit number.

I'm OK with the part about opening the file in a do block and using hGetLine to get each line as a string, and passing it on to a function that will modify the email to @example.com and pass that back to the caller.

Where I’m confused is taking the result and passing it on to another function to replace the ZIP code with a random ZIP. Converting the number to a string isn’t the problem; it’s generating the random number. From what I’ve read, random numbers “live” in the IO monad, so I have to somehow wrap the string back up into IO, and, well, I am totally mystified at this point. I haven't even a good clue of a starting point.

Any advice/hints, please?

@exallium
Copy link

Can you break it up into two functions?

  1. replace email
  2. replace zip

Do these in the same place you’re calling hGetLine or whatever, because i THINK that would be done within the IO monad?
You can then just bind the random number inline, and pass it to your pure fn that does the swap.

That’s my first thought anyhow.

This way too, your random number replacer, replaceZip :: Int -> String -> String, is very easily testible with a tool like quickcheck, since you are extracting the randomness.

@jdeisenberg
Copy link
Author

Thanks. I'm not sure what you mean by "quickcheck, since you are extracting the randomness" but I will read up on quickcheck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment