我正在尝试制作一个包含多种可能类型的集合.这是我希望它看起来的一个例子:
type Position = Vector2
type Velocity = Vector2
type Appearance = String
type Component = Position | Velocity | Appearance
let components = List<Dictionary<string, Component>>()
let pos = Dictionary<string, Position>()
components.Add(pos) // Type "Position" does not match with type "Component"
Run Code Online (Sandbox Code Playgroud)
我想声明仍然适合一般类型的特定类型.有没有办法可以像这样写我的代码?有没有比较惯用的方法呢?
我坚持使用foldr实现groupBy.出于某种原因,当我改变一个保护条件时,类型签名就会对我产生影响.
我可以编译这个,虽然它不正确:
groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' f xs = foldr step [] xs
where step x [] = [x] : []
step x (y:ys)
| True = []:(y:ys)
| otherwise = (x:y):ys
Run Code Online (Sandbox Code Playgroud)
但这不编译:
groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' f xs = foldr step [] xs
where step x [] = [x] : []
step x (y:ys)
| f x y = []:(y:ys)
| otherwise = …Run Code Online (Sandbox Code Playgroud)