## Archive for August, 2011

### Programming Praxis – First Non-Repeating Character

August 19, 2011

In today’s Programming Praxis exercise, our goal is to find the first character in a string that does not occur anywhere else in the string. Let’s get started, shall we?

Some imports:

```import Data.List
import qualified Data.Map as M```

To find the first non-repeated element, we mark each element as unique and insert them into a map. When a duplicate element is found, we remove its unique status. Afterwards, we search the list for the first unique element.

```firstUnique :: Ord a => [a] -> Maybe a
firstUnique xs = find (M.fromListWith (\_ _ -> False)
(zip xs \$ repeat True) M.!) xs```

Some tests to see if everything is working properly:

```main :: IO ()
main = do print \$ firstUnique "aabcbcdeef"   == Just 'd'
print \$ firstUnique "aabcbcfeed"   == Just 'f'
print \$ firstUnique "aabcbcdeefdf" == Nothing```

### Programming Praxis – Hett’s Problem 1.28

August 9, 2011

In today’s Programming Praxis, our goal is to sort a list of lists by length and by length frequency. Let’s get started, shall we?

A quick import:

```import qualified Data.List.Key as K
```

Sorting by length is trivial.

```byLength :: [[a]] -> [[a]]
byLength = K.sort length
```

Sorting by frequency of the list lengths is a bit more complicated since we need to group and ungroup the lists, but still a one-liner.

```byLengthFreq :: [[a]] -> [[a]]
byLengthFreq = concat . byLength . K.group length . byLength
```

Some tests to see if everything is working properly:

```main :: IO ()
main = do print \$ byLength ["abc","de","fgh","de","ijkl","mn","o"]
== ["o","de","de","mn","abc","fgh","ijkl"]
print \$ byLengthFreq ["abc","de","fgh","de","ijkl","mn","o"]
== ["o","ijkl","abc","fgh","de","de","mn"]
```