What makes this codewars answer work?

I am currently learning haskell and one of my best resources codewars. It is really useful because it gives me other people’s answers, which can help me learn more. I was wondering why this answer worked:

getAge :: (Integral a, Read a) => String -> a
getAge = read . take 1

I understand the first line am confused about the “.”. as well as the arguments that take and the read funcs are taking, because they aren’t like the normal params the functions contain. I have done testing and still don’t understand why it works. Any help is much appreciated!

(.) is the operator for composition: f . g is a function where the argument to that new function is first put into g and the result from this is put in to f - it’s like (f . g) x = f (g x).

You might see this here described as point-free style (points are the arguments to the function and as you don’t us the point …)

here is the same function in the style you might know:

getAge :: (Integral a, Read a) => String -> a
getAge s = read (take 1 s)

Now you probably see that take 1 s (or take 1as a function form String -> String there) takes a string as input and gives you the first character of the string but not as a Char (that would be head) but again as a String (remember: String = List Char)

Finally read here is a function from String -> a where a is both Integral and Read (without Read a you could not use read in the first place)

1 Like

Thank you I completely understand this now!

Me too! (You don’t give the link to the q it is answering.)

Now that @CarstenK has explained how the given code works, the 1 means it takes 1 character – that is, a digit. Most peoples’ ages take two (or more) digits to represent.

So I’d expect any useful getAge to need to ‘parse’ the beginning of the string; find some sort of delimiter, then read one, two or three chars into an Integral.