swift 遗忘函数语言的遗产值enum
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 遗忘函数语言的遗产值enum相关的知识,希望对你有一定的参考价值。
//playground for Oblivion functional programming language
enum OblVal:CustomStringConvertible {
case int(Int)
case str(String)
case bool(Bool)
indirect case map([String:OblVal])
case null
case undef
//indvidual initializers
init(val:Int){
self = .int(val)
}
init(val:String){
self = .str(val)
}
init(val:Bool){
self = .bool(val)
}
var description: String {
//recursive pretty printer for map cases
func repr(space:Int, map:[String:OblVal]) -> String {
let spacer = String(repeating: " ", count: space)
var keyval = ""
for (key, val) in map {
switch val {
case .map(let dict):
keyval += "\(spacer) \"\(key)\":\(repr(space:space+1, map:dict)),\n"
case .str(_):
keyval += "\(spacer) \"\(key)\":\"\(val)\",\n"
default:
keyval += "\(spacer) \"\(key)\":\(val),\n"
}
}
return "(\n\(keyval))"
}
switch self {
case .str(let val):
return String(val)
case .int(let val):
return String(val)
case .bool(let val):
return String(val)
case .map(let map):
return repr(space:0, map:map)
case .null:
return "null"
case .undef:
return "undef"
}
}
//computed getter variables
var int:Int {
switch self {
case .int(let val):
return val
default:
return 0
}
}
var str:String {
switch self {
case .str(let val):
return val
default:
return ""
}
}
var bool:Bool {
switch self {
case .bool(let val):
return val
default:
return false
}
}
subscript (index:OblVal) -> OblVal {
get {
switch self {
case .map(let map):
if let val = map[index.description] {
return val
}
else {
return OblVal.undef
}
default:
return OblVal.undef
}
}
set {
switch self {
case .map(var map):
switch index {
case.map(_):
break
default:
map[index.description] = newValue
self = OblVal.map(map)
}
default:
break
}
}
}
}
//function frame work
struct stdlib {
static func get(struc:inout OblVal, key:OblVal) -> OblVal {
return struc[key]
}
static func set(struc:inout OblVal, key:OblVal, val:OblVal) -> OblVal {
struc[key] = val
return struc
}
static func contains(struc:inout OblVal, key:OblVal) -> OblVal {
let val = struc[key]
switch val {
case .undef:
return OblVal(val:true)
default:
return OblVal(val:false)
}
}
}
以上是关于swift 遗忘函数语言的遗产值enum的主要内容,如果未能解决你的问题,请参考以下文章