
Hello, I had a question about type classes and data types. I want to create one class that has a function which depends upon a parameter from another class. I would assume that this can be done, but I can't seem to write code that does it. Can anybody tell me what is wrong? Here is an example of what I want to work: module Main where class Change c class State st where transitions :: (Change c) => st -> [(c, st)] data BinState = On | Off data BinChange = OnToOff | OffToOn -- get a list of (transition, newState) pairs: --binTransitions :: BinState -> [(BinChange, BinState)] -- doesn't work --binTransitions :: (State state, Change change) => state -> -- [(change, state)] -- doesn't work --binTransitions :: (State state1, State state2, Change change) => -- state1 -> [(change, state2)] -- doesn't work binTransitions On = [(OnToOff, Off)] binTransitions Off = [(OffToOn, On)] instance Change BinChange instance State BinState where transitions = binTransitions main = putStrLn "success." -- Thanks, -- -Chaim

Hello Chaim, Tuesday, January 29, 2008, 7:26:25 PM, you wrote: your approach is completely wrong (OOP-inspired, but haskell isn't OOP language). type class is common interface to different types. just for example: data BinState = On | Off data BinChange = OnToOff | OffToOn class MinValue a where minvalue :: a instance MinValue BinState where minvalue = On instance MinValue BinChange where minvalue = OnToOff here we define class with a function (class without functions hardly can be used for anything useful) and provide implementation of this function for different types. then, we can use it in any code: main = print (minValue :: BinChange) and in particular we can declare derived class. the advantage of derived class is that it can use all functions of base class. but it should add its own functions too, otherwise it will be again useless: class (MinValue a) => BoundedValue a where maxvalue :: a instance MinValue BinState where maxvalue = Off instance MinValue BinChange where maxvalue = OffToOn now, for values in BoundedValue class you can use both functions. also, you can use functions from MinValue class in default definitions of BoundedValue functions but if you just need to use functions from MinValue class, you don't need to declare one more class type classes can be compared with Java interfaces. they aren't 100% equal, though. read http://haskell.org/haskellwiki/OOP_vs_type_classes and especially its "further reading" section -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com
participants (2)
-
Bulat Ziganshin
-
Chaim Friedman