我正在尝试学习Haskell,但是我迷上了某些东西。到目前为止,我已经了解到函数签名符合以下约定:
<name> :: <type constraint A> => <input type A> -> <input type B> -> .. <input type X> -> <return type>
Run Code Online (Sandbox Code Playgroud)
因此,以我目前的理解为例:
-- 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
Run Code Online (Sandbox Code Playgroud)
然后我碰到了这个,这让我很困惑:
mate :: RandomGen g => Gene -> Gene -> Rand g Gene
Run Code Online (Sandbox Code Playgroud)
我知道函数名称是mate,并且它在类型g必须为type 时具有类型约束RandomGen,然后将type的两个值作为输入Gene。
但是,返回类型确实让我感到困惑。您如何解释这一点,并且有人可以向新手Haskeller解释吗?
如果您定义了自己的数据类型,例如
data MyType = A Int String
Run Code Online (Sandbox Code Playgroud)
然后A,您的数据构造函数实际上将是具有类型的函数
A :: Int -> String -> MyType
Run Code Online (Sandbox Code Playgroud)
并且您会这样称呼它以产生的值MyType。
A 42 "hello"
Run Code Online (Sandbox Code Playgroud)
这就是数据构造函数。
Haskell还具有类型构造函数。Rand是一个。就像函数值具有定义如何应用它们的函数类型一样,类型构造函数也具有确定如何应用它们的“函数” 类型。一种普通的老类型,如Int或String拼写*。的类型Rand是类型构造函数,* -> * -> *它的类型是:它接受两个类型,并从中产生一个类型。
因此,当您将Rand类型应用于g和时Gene,您将获得函数的返回类型,即Rand g Gene。
有关更多信息,请参阅“学习Haskell”这一章。
(“好吧,但是......什么是Rand g Gene?”,我听到你问。好吧,假设你的意思是这个Rand,Rand g Gene是代表会产生一个计算的值Gene,如果你的东西是能够运行的运行它Rand g的东西,如runRand现在,那不是你可以用唯一能做的Rand g Gene,因为它恰巧Rand g是...... 顿顿逼债 ......单子!对于很多上的概念,你真的应该读的东西像LYAH ..有很多准备工作可以向新手全面解释。)