Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function signature confusion

Tags:

haskell

I'm trying to learn Haskell, but I'm stumped on something. So far, I've come to understand that functions signatures conform to this convention:

<name> :: <type constraint A> => <input type A> -> <input type B> -> .. <input type X> -> <return type>

So, some examples with my current understanding are:

-- Returns input + 2
add2 :: Int -> Int
add2 x = x + 2

-- Returns the result of applying a function that takes an int and returns an int on an input int
adds2 :: (Int -> Int) -> Int -> Int
adds2 func x = func x

-- Returns a String with "Hello" prepended to the front
sayHello :: String -> String
sayHello name = "Hello " ++ name

Then I came across this which is what stumped me:

mate :: RandomGen g => Gene -> Gene -> Rand g Gene

I understand that the functions name is mate, and it has a type constraint where the g must be of type RandomGen, it then takes as input two values of type Gene.

However, it is the return type that is really confusing me. How do you interpret this and could anyone explain it to a novice Haskeller?

like image 716
Thomas Cook Avatar asked Jul 02 '19 20:07

Thomas Cook


1 Answers

If you defined yourself a data type like

data MyType = A Int String

then A, your data constructor, would effectively be a function with type

A :: Int -> String -> MyType

and you'd call it like this to produce a value of MyType.

A 42 "hello"

So that's data constructors.

Haskell also has type constructors. Rand is one. Just like function values have function types that define how they can be applied, type constructors have "function" kinds that determine how they can be applied. The kind of a regular old type like Int or String is spelled *. The kind of Rand, which is a type constructor, is * -> * -> *: it takes two types and produces a type from those.

So when you apply Rand to types g and Gene, you get the return type of your function, which is Rand g Gene.

For more, see this chapter of Learn You A Haskell.

("Okay, but... what is a Rand g Gene?", I hear you ask. Well, assuming you mean this Rand, Rand g Gene is a value that represents a computation that would produce a Gene if you run it in something that is capable of running Rand g things, such as runRand. Now, that's not the only thing you can do with a Rand g Gene, because it so happens Rand g is a... dun dun dun... monad! For a lot more on that concept, you really should read something like LYAH... there are a lot of preliminaries to get through to explain it in full to a newbie.)

like image 199
user11228628 Avatar answered Nov 06 '22 09:11

user11228628