我是 Haskell 编程和学习类型系统的新手,并且无法掌握空数据构造函数的基础。
以以下为例:
data Color = Red | Green | Blue | Indigo | Violet deriving Show
genColor:: Color
genColor = Red
Run Code Online (Sandbox Code Playgroud)
根据我的理解,Red、Green、Blue .. 是空数据构造函数,在使用时会构造“颜色”。
我无法理解的是,在传统的 OOP 语言中,您必须指定类型底层的原始类型——例如。颜色是否是字符串、整数、浮点数等。
在 Haskell 中,上面的代码运行得很好,为什么不需要呢?像这样构建类型系统的基本原理是什么?谢谢,所有帮助将不胜感激:)
以下面的代码为例..我定义了一些具有特定属性的可穿戴鞋子......(耐克、阿迪达斯、彪马)
data Shoe = Nike | Adidas | Puma deriving Show
class Wearable a where
forFeet :: a -> Bool
forUpperBody :: a -> Bool
comfortLevel :: a -> Int
purchasePrice :: a -> Int
from :: a -> String
instance Wearable Shoe where
forFeet _ = True
forUpperBody _ = False
comfortLevel Nike = 5
comfortLevel Adidas = 3
comfortLevel Puma = 8
purchasePrice Nike = 5
purchasePrice Adidas = 3
purchasePrice Puma = 3
from _ = "The …Run Code Online (Sandbox Code Playgroud) 如果这个问题听起来很愚蠢,请原谅我,我仍然是学习 Haskell 的初学者。
给定绑定运算符函数签名:
(>>=) :: m a -> (a -> m b) -> m b
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何从“m a”中提取“a”值以便函数(a -> m b)可以触发?haskell 是否在内部对此进行了抽象?
拿这个例子:
module Main where
main = print (reverseWords "lol")
reverseWords :: String -> [String]
reverseWords = words
Run Code Online (Sandbox Code Playgroud)
reverseWords函数不是针对任何参数的模式匹配,但函数运行和输出"[lol]"。
我在这里有两个问题:
Haskell 如何知道我是否正在words针对 的输入调用函数reverseWords?在这个语法中,看起来我只是在返回函数words。
为什么即使我没有在模式中提供任何输入参数,它也能成功运行reverseWords?
我有这个基本的 go 程序,它打印到控制台并调用 2 个 goroutines
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("hello")
go f("foo")
go f("bar")
time.Sleep(time.Second)
}
Run Code Online (Sandbox Code Playgroud)
输出如下——我想知道为什么在“foo”之前打印“bar”——是什么决定了 goroutines 的执行顺序?
hello : 0
hello : 1
hello : 2
bar : 0
bar : 1
bar : 2
foo : 0
foo : 1
foo : 2
Run Code Online (Sandbox Code Playgroud)