Maybe-like monad that gives breadcrumbs when Nothing occurs - haskell

I have two record types
data OptionalRecord = OptionalRecord
{ mFoo :: Maybe Foo
, mBar :: Maybe Bar
, mBaz :: Maybe Baz
}
data RequiredRecord = RequiredRecord
{ foo :: Foo
, bar :: Bar
, baz :: Baz
}
I have a function:
optionalToRequired :: OptionalRecord -> Maybe RequiredRecord
optionalToRequired OptionalRecord{..} =
do
foo <- mFoo
bar <- mBar
baz <- mBaz
return RequiredRecord{..}
This funcion works fine, but when it returns Nothing, I don't have any info about which field (or line in the do block) was Nothing.
Does anyone have any suggestions for an alternative that includes more info, like line number, that doesn't require a lot of embellishment?

William's suggestion in the comments is a good one: if you use Either instead of Maybe, then instead of Nothing, your computations can produce information about why they failed. But you do have to provide this information: you can't just get it automatically from the compiler with a line number for the bind. Indeed you can't introduce any information with a bind that doesn't come from the monadic value being binded, because this would break the Monad laws.
A common example of this is "What if I could count how many calls to >>= (or uses of <- in do-notation) there have been?". You can see why that doesn't work in the question Is it possible to create a Monad that count the number of instructions?.

As others have stated, Either a meets the requirements you've mentioned, but there is a very good reason for this: Either a behaves the same as Maybe as a Monad.
It can only hold a single value or no values.
An "error" value (Left foo or Nothing) short-circuits further computations whereas a "success" value (Right bar or Just bar) does not. (This means that you can only use Right as an indication of success and Left as an indication of an error.)
You can pattern-match "error" and "success" values at the end.
There is a large variety of Monad semantics out there, and having the concept of an error message isn't alone sufficient to take the place of Maybe.

Related

Can I declare a NULL value in Haskell?

Just curious, seems when declaring a name, we always specify some valid values, like let a = 3. Question is, in imperative languages include c/java there's always a keyword of "null". Does Haskell has similar thing? When could a function object be null?
There is a “null” value that you can use for variables of any type. It's called ⟂ (pronounced bottom). We don't need a keyword to produce bottom values; actually ⟂ is the value of any computation which doesn't terminate. For instance,
bottom = let x = x in x -- or simply `bottom = bottom`
will infinitely loop. It's obviously not a good idea to do this deliberately, however you can use undefined as a “standard bottom value”. It's perhaps the closest thing Haskell has to Java's null keyword.
But you definitely shouldn't/can't use this for most of the applications where Java programmers would grab for null.
Since everything in Haskell is immutable, a value that's undefined will always stay undefined. It's not possible to use this as a “hold on a second, I'll define it later” indication†.
It's not possible to check whether a value is bottom or not. For rather deep theoretical reasons, in fact. So you can't use this for values that may or may not be defined.
And you know what? It's really good that Haskell does't allow this! In Java, you constantly need to be wary that values might be null. In Haskell, if a value is bottom than something is plain broken, but this will never be part of intended behaviour / something you might need to check for. If for some value it's intended that it might not be defined, then you must always make this explicit by wrapping the type in a Maybe. By doing this, you make sure that anybody trying to use the value must first check whether it's there. Not possible to forget this and run into a null-reference exception at runtime!
And because Haskell is so good at handling variant types, checking the contents of a Maybe-wrapped value is really not too cumbersome. You can just do it explicitly with pattern matching,
quun :: Int -> String
quun i = case computationWhichMayFail i of
Just j -> show j
Nothing -> "blearg, failed"
computationWhichMayFail :: Int -> Maybe Int
or you can use the fact that Maybe is a functor. Indeed it is an instance of almost every specific functor class: Functor, Applicative, Alternative, Foldable, Traversable, Monad, MonadPlus. It also lifts semigroups to monoids.
Dᴏɴ'ᴛ Pᴀɴɪᴄ now,
you don't need to know what the heck these things are. But when you've learned what they do, you will be able to write very concise code that automagically handles missing values always in the right way, with zero risk of missing a check.
†Because Haskell is lazy, you generally don't need to defer any calculations to be done later. The compiler will automatically see to it that the computation is done when it's necessary, and no sooner.
There is no null in Haskell. What you want is the Maybe monad.
data Maybe a
= Just a
| Nothing
Nothing refers to classic null and Just contains a value.
You can then pattern match against it:
foo Nothing = Nothing
foo (Just a) = Just (a * 10)
Or with case syntax:
let m = Just 10
in case m of
Just v -> print v
Nothing -> putStrLn "Sorry, there's no value. :("
Or use the supperior functionality provided by the typeclass instances for Functor, Applicative, Alternative, Monad, MonadPlus and Foldable.
This could then look like this:
foo :: Maybe Int -> Maybe Int -> Maybe Int
foo x y = do
a <- x
b <- y
return $ a + b
You can even use the more general signature:
foo :: (Monad m, Num a) => m a -> m a -> m a
Which makes this function work for ANY data type that is capable of the functionality provided by Monad. So you can use foo with (Num a) => Maybe a, (Num a) => [a], (Num a) => Either e a and so on.
Haskell does not have "null". This is a design feature. It completely prevents any possibility of your code crashing due to a null-pointer exception.
If you look at code written in an imperative language, 99% of the code expects stuff to never be null, and will malfunction catastrophically if you give it null. But then 1% of the code does expect nulls, and uses this feature to specify optional arguments or whatever. But you can't easily tell, by looking at the code, which parts are expecting nulls as legal arguments, and which parts aren't. Hopefully it's documented — but don't hold your breath!
In Haskell, there is no null. If that argument is declared as Customer, then there must be an actual, real Customer there. You can't just pass in a null (intentionally or by mistake). So the 99% of the code that is expecting a real Customer will always work.
But what about the other 1%? Well, for that we have Maybe. But it's an explicit thing; you have to explicitly say "this value is optional". And you have to explicitly check when you use it. You cannot "forget" to check; it won't compile.
So yes, there is no "null", but there is Maybe which is kinda similar, but safer.
Not in Haskell (or in many other FP languages). If you have some expression of some type T, its evaluation will give a value of type T, with the following exceptions:
infinite recursion may make the program "loop forever" and failing to return anything
let f n = f (n+1) in f 0
runtime errors can abort the program early, e.g.:
division by zero, square root of negative, and other numerical errors
head [], fromJust Nothing, and other partial functions used on invalid inputs
explicit calls to undefined, error "message", or other exception-throwing primitives
Note that even if the above cases might be regarded as "special" values called "bottoms" (the name comes from domain theory), you can not test against these values at runtime, in general. So, these are not at all the same thing as Java's null. More precisely, you can't write things like
-- assume f :: Int -> Int
if (f 5) is a division-by-zero or infinite recursion
then 12
else 4
Some exceptional values can be caught in the IO monad, but forget about that -- exceptions in Haskell are not idiomatic, and roughly only used for IO errors.
If you want an exceptional value which can be tested at run-time, use the Maybe a type, as #bash0r already suggested. This type is similar to Scala's Option[A] or Java's not-so-much-used Optional<A>.
The value is having both a type T and type Maybe T is to be able to precisely identify which functions always succeed, and which ones can fail. In Haskell the following is frowned upon, for instance:
-- Finds a value in a list. Returns -1 if not present.
findIndex :: Eq a => [a] -> a -> Int
Instead this is preferred:
-- Finds a value in a list. Returns Nothing if not present.
findIndex :: Eq a => [a] -> a -> Maybe Int
The result of the latter is less convenient than the one of the former, since the Int must be unwrapped at every call. This is good, since in this way each user of the function is prevented to simply "ignore" the not-present case, and write buggy code.

How do I reuse an intermediate value in chain of Haskell Either binds?

I'm sure this has been answered but apparently I don't know what to search for.
I am working on my first non-trivial Haskell program -- a simulation of a card game I enjoy. I have the program working but there is a situation that I am certain can be handled better.
If I have a series of binds which are Either String TypeChangesBasedOnTheFunction.
playerInput <- getLine
case playerInput of
{- CASE STUFF NOT IMPORTANT TO THIS QUESTION -}
_ -> do let handValue = inputHasAllValidChars playerInput >>= makeDeckFromString >>= deckSubset (getCurrentPlayersDeck gameState) >>= whatHandRepresents >>= handBeatsCurrentTopTrick
Very soon after this part of the code runs, I need the value for whatHandRepresents. I can just run the same chain of binds again but I am certain there must be a better way by storing the value when it is determined in the code above.
My question is, is it possible to store this value. If so, how?
You have to thread it all the way back up to where you need it.
repr <- case playerInput of
-- now you have to return something of the appropriate type,
-- say, `Left "didn't get it"`, from these other cases.
_ -> do let repr = ... >>= whatHandRepresents
handValue = repr >>= handBeatsCurrentTopTrick
-- use handValue
return repr
-- now use repr :: Either String HandRepresentationOrWhatever
I sure hope you actually are using handValue within the default case and not trying to assign it for use later on. It will only be in scope within that case; if you want to use it afterward you have to return it also, just like repr (e.g. in a tuple).

Getting 'a' value from 'Maybe a' return type in Haskell

I have a Haskell function eval :: WExp -> Memory -> WValue with a bunch of different instances of itself for different cases. For now, knowledge about WExp, Memory, and WValue is not relevant. My problem is that, for a specific instance of eval, I am using a lookup function, which takes the parameter of eval (a string in this case) searches a list of key-value pairs for that string. Note that this lookup function is not the one included in the Prelude; it is self-defined within the .hs file. If the string is found, the value associated with it is returned, but if it is not found, Nothing is returned. Because of the Nothing case, the type of lookup is actually Maybe a, where a would be a WValue in this case. Because eval would return a Maybe WValue, the compiler obviously complains that the type is not WValue.
I thought that there might be some kind of general method to extract the a value from any function that returns Maybe a.
Do this
do
input <- getUserInput
result <- lookup input structure
case result of
Just a -> putStrLn $ "I'm so happy you chose "++show a++"."
Nothing -> putStrLn $ "So sorry; "++input++" is not a valid option."
Don't do this
do
input <- getUserInput
result <- lookup input structure
case result of
Just a -> putStrLn $ "I'm so happy you chose "++show a++"."
Nothing -> error $ input ++ " is not a valid option."
This is bad because your program just goes splat if the user input is wrong.
Really don't do this
There is a function called fromJust that attempts to pull a value out of a Maybe and throws an error if it finds Nothing. It looks like
fromJust :: Maybe a -> a
fromJust (Just a) = a
fromJust Nothing = error "Oops, you goofed up, fool."
This makes it hard to see what went wrong.
And really, really don't do this
But if you want to play with fire, you can try it just for fun. This will attempt to get a value out of a Maybe and crash real hard if it finds Nothing. By "crash real hard" I mean you'll get a segmentation fault if you're lucky, and you'll publish your private keys on the web if you're not.
{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
module Unsafe.FromJust (unsafeFromJust) where
-- Clear sign of bad news
import Unsafe.Coerce (unsafeCoerce)
-- This creates a "closed kind" with types
-- 'JustType and 'NothingType. You could just
-- define datatypes called JustType and NothingType,
-- but this makes the intent clearer.
data MaybeType = JustType | NothingType
data M (t::MaybeType) a where
-- The order of these constructors must not
-- be changed, because this type must look,
-- at runtime, exactly like a Maybe
N :: M 'NothingType a
J :: a -> M 'JustType a
-- A safe sort of fromJust for M.
fromJ :: M 'JustType a -> a
fromJ (J a) = a
-- Really, seriously unsafe.
unsafeFromJust :: Maybe a -> a
unsafeFromJust m = fromJ (unsafeCoerce m)
The function you are looking for is maybe defined in Prelude.
You need to decide on what to return if the expression is Nothing. Lets say you want to get empty string "" for Nothing. Then the following will let you get out of Maybe boxes.
Prelude> maybe "" id (Just "hello")
"hello"
Prelude> maybe "" id (Nothing)
""
If you know that the lookup is successful, and that the Maybe a is actually Just a, you can simply pattern match:
let (Just val) = lookup ...
and there you have your val::a out of your Maybe a. Note that this is unsafe code which will ungracefully throw an error if lookup returns a Nothing.
Well, you got yourself into a quagmire because the type of your lookup says that it could fail. Haskell forces you in this case to deal with the possibility that such a failure will occur. This is the case if lookup returns Nothing.
If you are really sure that lookup never fails (maybe because you preprocessed and type-checked the program, or you really trust it :) ) you could use fromJust from Data.Maybe. Note that is is really just a band-aid solution because fromJust will produce a (Haskell) runtime error on its own if called with Nothing.

Haskell - assert a function was called

Is it possible to verify that a function was called in Haskell HSpec?
Assuming I had two functions foo and bar that transform my data.
foo :: Stuff -> Stuff
bar :: Stuff -> Stuff
And I have a function that applies either foo or bar on Stuff depending on whether it received 'f' or 'b' as its second argument and returns the result of the applied function.
apply :: Stuff -> Char -> Stuff
And In my tests, I have tested each of the functions foo and bar comprehensively that i would not want to test there effect with in apply.
Is it possible for me to verify that a function foo or bar was called? depending on what argument is passed to apply?
"I'm thinking more TDD, like in an OOP language. Is such a thing possible in Haskell?"
A better question is "is such a thing necessary in Haskell?" ;-)
[I realise that is not the question you actually asked. Feel free to ignore this answer.]
In an OO language, we build objects that talk to other objects to get their job done. To test such an object, we build a bunch of fake objects, hook the real object up to the fake ones, run the method(s) we want to test, and assert that it calls faked methods with the expected inputs, etc.
In Haskell, we write functions. The only thing a pure function does is take some input, and produce some output. So the way to test that is to just run the thing, feeding it known inputs and checking that it returns known outputs. What other functions it calls in the process of doing that doesn't matter; all we care about is whether the answer is right.
In particular, the reason we don't usually do this in OOP is that calling some arbitrary method might cause "real work" to happen — reading or writing disk files, opening network connections, talking to databases and other servers, etc. If you're just testing one part of your code, you don't want the test to depend on whether some database is running on a real network server somewhere; you just want to test one little part of your code.
With Haskell, we separate anything that can affect the Real World from stuff that just does data transformations. Testing stuff that just transforms data in memory is delightfully trivial! (Testing the parts of your code that do interact with the Real World is still hard, in general. But hopefully those parts are very small now.)
The Haskell test style of choice seems to be property-based testing. For example, if you've got a function to solve an equation, you write a QuickCheck property that randomly generates 100 equations, and for each one, it checks whether the number returned actually solves the original equation or not. It's a tiny handful of code that automatically tests just about everything you'd ever want to know! (But not quite: You need to make sure that the "randomly" chosen equations actually test all the code paths you care about.)
(No exactly Haskell, but close.)
fooP = point . foo
-- testable property: forall s. foo s = runIdenity $ fooP s
barP = point . bar
-- similar testable property
fooAndWitness :: Stuff -> Writer String Stuff
fooAndWitness = fooM >> tell "foo"
-- testable property forall s. (foo s, "foo") = runWriter $ fooAndWitness s
barAndWitness :: Stuff -> Writer String Stuff
barAndWitness = barM >> tell "bar"
-- similar testable property
applyOpen :: Pointed p => (Stuff -> p Stuff) -> (Stuff -> p Stuff) -> Stuff -> Char -> p Stuff
applyOpen onF _ x 'f' = onF x
applyOpen _ onB x 'b' = onB x
applyOpen _ _ x _ = point x
-- semi-testable property (must fix p):
-- forall f b s c. let a = applyOn f b s c in a `elem` [f s, b s, point s]
-- In particular, if we choose p carefully we can be, at least stochastically,
-- sure that either f, b, or neither were called by having p = Const [Int], and running several tests
-- where two random numbers are chosen, `f _ = Const $ [rand1]`, and `b _ = Const $ [rand2]`
-- and verifying we get one of those numbers, which could not have been known when applyOpen was written.
applyM = applyOpen fooM barM
-- similar testable property, although but be loose the "rigged" tests for variable f/b, so
-- some of our correctness may have to follow from the definition.
apply = (runIdentity .) . applyM
-- similar testable property and caveat
Pointed is a type class that fits between Functor and Applicative and provides point with the same semantics as pure or return. It's only law follows from parametricity: (. point) . fmap = (point .)

Converting IO Int to Int

I've created a combobox from converting a xmlWidget to a comboBox with the function castTocomboBox and now I want to get the text or the index of the active item. The problem is that if I use the comboBoxGetActive function it returns an IO Int result and I need to know how can I obtain the Int value. I tried to read about monads so I could understand what one could do in a situation like this but I don't seem to understand. I appreciate all the help I can get. I should probably mention that I use Glade and gtk2hs.
As a general rule you write something like this:
do
x <- somethingThatReturnsIO
somethingElseThatReturnsIO $ pureFunction x
There is no way to get the "Int" out of an "IO Int", except to do something else in the IO Monad.
In monad terms, the above code desugars into
somethingThatReturnsIO >>= (\x -> somethingElseThatReturnsIO $ pureFunction x)
The ">>=" operator (pronounced "bind") does the magic of converting the "IO Int" into an "Int", but it refuses to give that Int straight to you. It will only pass that value into another function as an argument, and that function must return another value in "IO". Meditate on the type of bind for the IO monad for a few minutes, and you may be enlightened:
>>= :: IO a -> (a -> IO b) -> IO b
The first argument is your initial "IO Int" value that "comboBoxGetActive" is returning. The second is a function that takes the Int value and turns it into some other IO value. Thus you can process the Int, but the results of doing so never escape from the IO monad.
(Of course there is the infamous "unsafePerformIO", but at your level of knowledge you may be certain that if you use it then you are doing it wrong.)
(Actually the desugaring is rather more complicated to allow for failed pattern matches. But you can pretend what I wrote is true)
Well, there is unsafePerformIO: http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/System-IO-Unsafe.html#v:unsafePerformIO
(If you want to know how to find this method: Go to http://www.haskell.org/hoogle and search for the signature you need, here IO a -> a)
That said, you probably heard of "What happens in IO stays in IO". And there are very good reasons for this (just read the documentation of unsafePerformIO). So you very likely have a design problem, but in order to get help from experienced Haskellers (I'm certainly not), you need to describe your problem more detailed.
To understand what those types are –step by step–, first look up what Maybe and List are:
data Maybe a = Nothing | Just a
data [a] = [] | a : [a]
(Maybe a) is a different type than (a), like (Maybe Int) differs from (Int).
Example values of the type (Maybe Int) are
Just 5 and Nothing.
A List of (a)s can be written as ([ ] a) and as ([a]). Example values of ([Int]) are [1,7,42] and [ ].
Now, an (IO a) is a different thing than (a), too: It is an Input/Output-computation that calculates a value of type (a). In other words: it is a script or program, which has to be executed to generate a value of type (a).
An Example of (IO String) is getLine, which reads a line of text from standard-input.
Now, the type of comboBoxGetActive is:
comboBoxGetActive :: ComboBoxClass self => self -> IO Int
That means, that comboBoxGetActive is a function (->) that maps from any type that has an instance of the type-class ComboBoxClass (primitive type-classes are somehow similar to java-interfaces) to an (IO Int). Each time, this function (->) is evaluated with the same input value of this type (self) (whatever that type is), it results in the same value: It is always the same value of type (IO Int), that means that it is always the same script. But when you execute that same script at different times, it could produce different values of type (Int).
The main function of your program has the type (IO ()), that means that the compiler and the runtime system evaluate the equations that you program in this functional language to the value of main, which will be executed as soon as you start the program.

Resources