Skip to content

Instantly share code, notes, and snippets.

@dictav
Last active August 29, 2015 14:03
Show Gist options
  • Save dictav/fea0f4f5ae5b4740369f to your computer and use it in GitHub Desktop.
Save dictav/fea0f4f5ae5b4740369f to your computer and use it in GitHub Desktop.
型クラスとかそんなの意識したけど結局できなかったもの
package main
import (
"fmt"
)
type Any interface{}
type Incrementer interface {
increment() Any
}
type myInt int
func (val myInt) increment() Any {
return val + 1
}
type myString string
func (str myString) increment() Any {
return "incremented string"
}
func inc(val Incrementer) Any {
return val.increment()
}
func main() {
a := myInt(1)
fmt.Println(inc(a))
b := myString("abc")
fmt.Println(inc(b))
}
#import <Foundation.h>
@protocol Incremantable <NSObject>
- (instancetype)increment;
@end
@interface NSNumber(Incrementable)<Incremantable> @end
@implementation NSNumber (Incrementable)
- (instancetype)increment
{
return @(self.integerValue + 1);
}
@end
@interface NSString (Incrementable) <Incremantable> @end
@implementation NSString (Incrementable)
- (instancetype)increment
{
return @"incremented string";
}
@end
id inc(id<Incremantable> value) {
return [value increment];
}
int main(int argc, char * argv[])
{
@autoreleasepool {
NSLog(@"%@", inc(@1)); // 2
NSLog(@"%@", inc(@"abc")); // incremented string
return 0;
}
}
protocol Incrementable {
func increment() -> Self
}
func inc<T:Incrementable>(obj: T) -> T? {
let val = obj.increment()
return val
}
extension Int : Incrementable {
func increment() -> Int {
return self + 1
}
}
extension String : Incrementable {
func increment() -> String {
var str = ""
for code in self.unicodeScalars {
str += String( UnicodeScalar(code.value + 1) )
}
return str
}
}
inc(10) // 11
inc("abc") // "bcd"
@dictav
Copy link
Author

dictav commented Jul 5, 2014

発想が型クラスではないな

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment