我正在学习Haskell。这是一个简单的示例,但我想了解一下为什么在以下示例中无法在lambda函数内部使用模式匹配的概念(即,为什么filterfold'函数运行但filterfold'给出运行时错误):
-- Runs
filterfold' :: (a -> Bool) -> [a] -> [a]
filterfold' p zs = foldr (\y zs -> if (p y) then y:zs else zs) [] zs
-- Runtime error: Non-exhaustive patterns in lambda
filterfold :: (a -> Bool) -> [a] -> [a]
filterfold p (z:zs) = foldr (\y (z:zs) -> if (p y) then y:(z:zs) else (z:zs)) [] (z:zs)
Run Code Online (Sandbox Code Playgroud) getter计算属性和返回值的变量之间是否存在差异?例如,以下两个变量之间有区别吗?
var NUMBER_OF_ELEMENTS1: Int {
return sampleArray.count
}
var NUMBER_OF_ELEMENTS2: Int {
get {
return sampleArray.count
}
}
Run Code Online (Sandbox Code Playgroud) 我想从数组中创建一个字典,并为每个字符分配一个新的自定义对象.我稍后会对这些对象做些什么.我怎样才能做到这一点?
var cals = [1,2,3]
// I want to create out of this the following dictionary
// [1:ReminderList() object, 2:ReminderList() object, 3:ReminderList() object]
let calendarsHashedToReminders = cals.map { ($0, ReminderList()) } // Creating a tuple works!
let calendarsHashedToReminders = cals.map { $0: ReminderList() } // ERROR: "Consecutive statements on a line must be separated by ';'"
Run Code Online (Sandbox Code Playgroud) 我想在映射到字符串数组的int字典中查找字符串值.我可以使用下面的代码来处理映射到字符串但不是字符串数组的整数字典.我怎样才能做到这一点?我尝试在我的过滤器中嵌套另一个过滤器,但没有运气.
let dict = [1 : ["one", "two"], 2 : ["red", "green"], 3 : ["World", "are", "you"]]
// Doesn't work for array of strings.
let keys = dict.filter {
return $0.1.containsString("are") // Should return 3
}.map {
return $0.0
}
Run Code Online (Sandbox Code Playgroud) 我正在学习Haskell.我定义了以下函数(我知道我不需要addToList,我也可以做无点符号我只是在玩语言概念):
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = addToList (f x) map f xs
where
addToList :: a -> [a] -> [a]
addToList x [] = [x]
addToList x xs = x:xs
Run Code Online (Sandbox Code Playgroud)
这会产生编译错误:
with actual type `(a0 -> b0) -> [a0] -> [b0]'
Relevant bindings include
f :: a -> b (bound at PlayGround.hs:12:5)
map :: (a -> b) -> [a] -> [b] (bound at PlayGround.hs:11:1)
Probable …Run Code Online (Sandbox Code Playgroud) 我想建立一本字典的字典。在 Swift 中,如何声明一个具有字符串键和相同类型字典值的字典?我需要能够拥有无限的巢穴。(有点像使用节点构建树。只不过它不是树,而是字典。)
我尝试使用 AnyObject,但出现转换错误:
var node1: Dictionary<String, AnyObject?> = ["foo" : nil]
var node2: Dictionary<String, AnyObject?> = ["bar" : node1] // ERROR: Cannot convert value of type 'Dictionary<String, AnyObject?>' (aka 'Dictionary<String, Optional<AnyObject>>') to expected dictionary value type 'Optional<AnyObject>'
Run Code Online (Sandbox Code Playgroud)
是否有类型安全的方法来执行此操作(即不使用 AnyObject?)