[Haskell-cafe] testing for same characters in lists of strings

Krzysztof Kościuszkiewicz k.kosciuszkiewicz+haskell at gmail.com
Mon Apr 7 23:25:24 EDT 2008


On Mon, Apr 07, 2008 at 07:51:05PM -0700, Jackm139 wrote:

> I have an assignment to make a program to test whether two lists use the
> same characters for each string.
> e.g.
> 
> sameCharacter ["rock", "cab"] ["cork", "abc"]
> True
> 
> My plan to tackle this was to use:
> nub to eliminate duplications,
> sort to put the characters in order,
> and map to put characters together.. and then somehow check to see if these
> characters are the same.

Probably you won't need to eliminate duplicates, sorting would be enough
(although it depends on the assignment details).

Comparing Chars (and Strings) can be accomplished with

> (==) :: (Eq a) => a -> a -> Bool

> My problem right now is just figuring out how to make a function that uses
> these three functions to give me a list of tuples.

To get list of tuples you can use

> zip :: [a] -> [b] -> [(a, b)]

or alternatively you can apply a binary function in a "pairwise way"
using

> zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

as in

> zipWith (+) [1, 2] [3, 4]
> [4, 6]

For chaining functions you can use function composition:

> (.) :: (b -> c) -> (a -> b) -> a -> c

as in

> not :: Bool -> Bool
> and :: [Bool] -> Bool
> nand :: [Bool] -> Bool
> nand = not . and

or do without composition by specifying all arguments:

> nand xs = not (and xs)

Hope this helps,
-- 
Krzysztof Kościuszkiewicz
Skype: dr.vee,  Gadu: 111851,  Jabber: kokr at jabberpl.org
"Simplicity is the ultimate sophistication" -- Leonardo da Vinci


More information about the Haskell-Cafe mailing list