3 ms·
> I don't normally think of values in other languages as having methods directly or an interface like this. If I understand you correctly, Haskell has this, an
by runeks 9y ago
> I don't normally think of values in other languages as having methods directly or an interface like this.
If I understand you correctly, Haskell has this, and it's basically all you have to implement generic interfaces in Haskell.
A simple example is the Bounded class, whose interface exposes two functions: minBound and maxBound. So, for example, all integers (int8, uint8, int16, uint16, [...], uint64) have upper and lower bounds, and can implement this interface, like so (Word8 is uint8):
instance Bounded Word8 where
minBound = 0
maxBound = 255
This forces all instances of a class to be a type that contains all information needed to implement the interface (as opposed to some construct that needs to accumulate state at runtime in order for it to work properly), which means the compiler can check almost everything at compile-time.
This is where monads come in, which is simply a value that describes a computation, e.g. fetching a value of a specific type from a web server at a given URL. So, in Haskell, all that exists are values, and they're also used to represent an operation which, at runtime, performs a certain action.
So, for example, the following function:
concatStr :: String -> String -> String
is a pure function which only modifies it's two arguments (String and String) and produces a String, whereas
printReadStdIn :: String -> IO String
printReadStdIn str = do
putStrLn str
getLine
is a function which, when given a String, will -- at runtime -- print out a String and read a String from standard input, and this String will be available inside the IO monad (which can implement interfaces, because it's just a value).