0
type FreqTable = [(Char, Int)]

fTable :: String -> FreqTable 
fTable s = [sort $ s, i+1]
    where i = 0

As you can see I am trying to return a tuple, but I can't understand why what I have returned isn't acceptable. Obviously this isn't a completed program that returns a frequency table yet but I am just trying to understand how to return this type FreqTable at the moment.

Also any hints to how I would go about creating the frequency table would be much appreciated as I am quite new to Haskell, I don't want the answer just some stepping stones.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Howard
  • 53
  • 2
  • 9
  • If you want to return a pair, *make a pair*! You've made the list part using `[` and `]`, now make a pair by writing `[(sort s, i+1)]`. – crockeea Nov 12 '14 at 14:43
  • I just tried that and when I try to load it I "parse error (possibly incorrect indentation or mismatched brackets)" back? – Howard Nov 12 '14 at 14:51
  • 1
    Try answers [here](http://stackoverflow.com/questions/7108559/how-to-find-the-frequency-of-characters-in-a-string-in-haskell), or [here](http://stackoverflow.com/questions/13517114/count-frequency-of-each-element-in-a-list). Try [google](https://www.google.ru/search?q=haskell+frequency+count&oq=haskell+freque&aqs=chrome.1.69i57j0l5.7226j0j7&sourceid=chrome&es_sm=122&ie=UTF-8) first. –  Nov 12 '14 at 15:00

1 Answers1

3

A typical element of [(Char,Int)] would look like

[('a',3),('b',4)]

writing

[sort $ s, i+1]

puts a string and an integer in the same list, which is an error since lists must be homogeneous (composed of things having the same type).

By then way, sort $ s is the same as sort s, so I'll use the latter from now on.

Note that the above is not even a list of pairs. Let's try adding a pair:

[(sort s, i+1)]

this is a correct list, but has type [(String,Int)], not [(Char,Int)], hence it still won't do.

You need to tear the (sorted) string apart to individual Chars. This can be done e.g. with a list comprehension

[(c,1) | c <- sort s ]

this is not what you want, but at least has the right type. Now you have to add all these 1s for the same c...

If you want to leverage some library functions, lookup function group in the standard library.

chi
  • 111,837
  • 3
  • 133
  • 218