coding style - Unwrapping datatypes in Haskell without extraneous code -


say have

x = 2 

is there way (preferrably builtin mechanism/function) use x in single statement such if just, 2 automatically unwrapped , used, , if nothing, exception raised?

that is,

(f x) + 2 == 4 if x == 2, , raises exception if x == nothing.

data.maybe.fromjust has been mentioned other answers already:

fromjust :: maybe -> fromjust nothing  = error "maybe.fromjust: nothing" fromjust (just x) = x 

there's maybe (found in both prelude , data.maybe):

maybe :: b -> (a -> b) -> maybe -> b maybe n _ nothing  = n maybe _ f (just x) = f x 

fromjust can written using maybe:

fromjust = maybe (error "maybe.fromjust: nothing") id 

as can see, maybe allows flexibility in handling both cases without requiring pattern matching:

\x -> maybe 0 (+ 2) x  -- nothing -> 0, 2 -> 4 

similarly, prelude , data.either have either :: (a -> c) -> (b -> c) -> either b -> c:

\x -> either (subtract 1) (* 2) x  -- left 5 -> 4, right 3 -> 6 

if define data type

data mydatatype   = typea { foo :: int, bar :: string }   | typeb { foo :: int,                baz :: () }   | typec {             bar :: string, baz :: () } 

like this, end partial functions accessors.

foo :: mydatatype -> int bar :: mydatatype -> string baz :: mydatatype -> () 

they're called partial functions, opposed total functions, because return results subset of inputs.

foo (typea { foo = 15, bar = "hello!" })  -- 15 bar (typeb { foo = 12345679, baz = () })  -- error 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -