user2502169
user2502169

Reputation: 35

How to add characters to the output of a permutation in Haskell?

I want to make in Haskell a application that gives from a couple of characters all possibilities. That works with the permutation function. But now I want to add to the output of every word in the list a prefix and a suffix. Like:

Input:

combinations "prefix" "sufix" "randomletters"

Output (something like this)

["prefixrandomletters", "prefixrandomletters","prefixrandomletters","prefixrandomletters","suffixrandomletters","suffixrandomletters","suffixrandomletters","suffixrandomletters","suffixrandomletters",]

Background of the application: Like scrabble. First the prefix is like 2 letters that the word can start with. Then 2 letters that the word can end with. Then the letters you have in your hand.

Upvotes: 0

Views: 153

Answers (1)

huon
huon

Reputation: 102106

You can map a function that adds the prefix:

combinations pre suf letters = prefixed ++ suffixed
  where
    perms = permutations letters
    prefixed = map (\x -> pre ++ x) $ perms
    suffixed = ...

The way to solve this is to break the problem down, as you have started doing:

  • create a function to give every permutation (permutation)
  • create functions to add the prefix & suffix (\x -> pre ++ x etc)
  • apply these functions to every permutation (map) to create two lists of words
  • combine the two lists of words (++)

Upvotes: 1

Related Questions