Truth tables in libreoffice calc: existence of the implies and equivalence functions? - logical-operators

I'm trying to construct a truth table in Libreoffice Calc and can't seem too find the implies- nor equivalence functions in the documentation. Do they exist and if so, what are they called?

You could write your own functions. From the menu choose "Tools" -> "Macros" -> "Organize Macros" -> "LibreOffice Basic...". In the new window choose "Tools" -> "Select Module". Create a new module or select and existing and click the "Edit" button. In the code pane you can now define your functions, for example:
Function IMPLIES (A As Boolean, B As Boolean) As Boolean
IMPLIES = (NOT A) OR B
End Function
Function EQUIVALENT (A As Boolean, B As Boolean) As Boolean
EQUIVALENT = (A AND B) OR ((NOT A) AND (NOT B))
End Function
Save and you can use the functions like regular functions in your sheet, e.g. =IMPLIES(TRUE, FALSE) or =EQUIVALENT(FALSE, TRUE).

Related

Confused about F# method signature syntax

I am supposed to write a small program in F# for a uni assignment. One of the exercises says to create a filter method with this signature:
filter : ('a -> bool) -> list<'a> -> list<'a>. But I am struggling to properly interpret this syntax. The docs say the syntax for creating a method is
let [inline] function-name parameter-list [ : return-type ] = function-body. But how does my example fit into this? Is it a function which takes no parameters but returns three values?
The function should filter a list given a predicate which is simple enough, but if it doesn't take any parameters, how should I pass a predicate and list? I am sure I'm missing something major because I can't wrap my head around it.
The documentation you may be referring to tells you how to implement a function. The signature you've been given, however, is the desired function's type. F# types are documented here: https://learn.microsoft.com/dotnet/fsharp/language-reference/fsharp-types
Specifically, the documentation says that in its simplest form, a function has the type parameter-type1 -> return-type, but when it has more parameters, it generally takes the form parameter-type1 -> parameter-type2 -> ... -> return-type.
In F#, functions are values, so the desired filter is a value that happens to be a function. The function should take two inputs: ('a -> bool) and list<'a>, and return a value of the type list<'a>.
One of the inputs is a function in its own right: ('a -> bool).
Technically, this is saying that filter is a function which takes a predicate function of type 'a -> bool and returns a function which takes a list<'a> and returns another value of type list<'a>.
This is because functions only transform one value into another, but either of those values can be a function.
As a practical matter, filter takes two arguments: that predicate function which take one 'a value and returns a boolean, and a list<'a>.
The simplest answer to your question is that that function takes two arguments and returns a value:
('a -> bool) // arg 1
-> list<'a> // arg 2
-> list<'a> // return value
In F#, function arguments can also be thought of as part of the return value because of partially applied functions e.g. you can think of the above as "given the first arg, return back a new function that expects the second arg and gives back the filtered list".
('a -> bool) // arg
-> (list<'a> -> list<'a>) // return value

Haskell Data.Map lookup AND delete at the same time

I was recently using the Map type from Data.Map inside a State Monad and so I wanted to write a function, that looks up a value in the Map and also deletes it from the Map inside the State Monad.
My current implementation looks like this:
lookupDelete :: (Ord k) => k -> State (Map k v) (Maybe v)
lookupDelete k = do
m <- get
put (M.delete k m)
return $ M.lookup k m
While this works, it feels quite inefficient. With mutable maps in imperative languages, it is not uncommon to find delete functions, that also return the value that was deleted.
I couldn't find a function for this, so I would really appreciate if someone knows one (or can explain why there is none)
A simple implementation is in terms of alterF:
lookupDelete :: Ord k => k -> State (Map k v) (Maybe v)
lookupDelete = state . alterF (\x -> (x, Nothing))
The x in alterF's argument is the Maybe value stored at the key given to lookupDelete. This anonymous function returns a (Maybe v, Maybe v). (,) (Maybe v) is a functor, and basically it serves as a "context" through which we can save whatever data we want from x. In this case we just save the whole x. The Nothing in the right element specifies that we want deletion. Once fully applied, alterF then gives us (Maybe v, Map k v), where the context (left element) is whatever we saved in the anonymous function and the right element is the mutated map. Then we wrap this stateful operation in state.
alterF is quite powerful: lots of operations can be built out of it simply by choosing the correct "context" functor. E.g. insert and delete come from using Identity, and lookup comes from using Const (Maybe v). A specialized function for lookupDelete is not necessary when we have alterF. One way to understand why alterF is so powerful is to recognize its type:
flip alterF k :: Functor f => (Maybe a -> f (Maybe a)) -> Map k a -> f (Map k a)
Things with types in this pattern
SomeClass f => (a -> f b) -> s -> f t
are called "optics" (when SomeClass is Functor, they're called "lenses"), and they represent how to "find" and "mutate" and "collate" "fields" inside "structures", because they let us focus on part of a structure, modify it (with the function argument), and save some information through a context (by letting us choose f). See the lens package for other uses of this pattern. (As the docs for alterF note, it's basically at from lens.)
There is no function specifically for "delete and lookup". Instead you use a more general tool: updateLookupWithKey is "lookup and update", where update can be delete or modify.
updateLookupWithKey :: Ord k =>
(k -> a -> Maybe a) -> k -> Map k a -> (Maybe a, Map k a)
lookupDelete k = do
(ret, m) <- gets $ updateLookupWithKey (\_ _ -> Nothing) k
put m
pure ret

Haskell HDBC.Sqlite3 fetchAllRows

Since I am an absolute Haskell beginner, but determined to conquer it, I am asking for help again.
using:
fetchData2 = do
conn <- connectSqlite3 "dBase.db"
statement <- prepare conn "SELECT * FROM test WHERE id > 0"
execute statement []
results <- fetchAllRows statement
print results
returns:
[[SqlInt64 3,SqlByteString "Newco"],[SqlInt64 4,SqlByteString "Oldco"],[SqlInt64 5,SqlByteString "Mycom"],[SqlInt64 4,SqlByteString "Oldco"],[SqlInt64 5,SqlByteString "Mycom"]]
Is there a clever way to clean this data into Int and [Char], in other words omitting types SqlInt64 and SqlByteString.
You could define a helper:
fetchRowFromSql :: Convertible SqlValue a => Statement -> IO (Maybe [a])
fetchRowFromSql = fmap (fmap (fmap fromSql)) . fetchRow
The implementation looks a bit daunting, but this is just because we need to drill down under the layered functors as you already noted (first IO, then Maybe and lastly []). This returns something that is convertible from a SqlValue. There are a bunch of these defined already. See e.g. the docs. An example (using -XTypeApplications):
fetchRowFromSql #String :: Statement -> IO (Maybe [String])
I should perhaps add that the documentation mentions that fromSql is unsafe. Meaning that if you try to convert a sql value to an incompatible Haskell value the program will halt.

Idiomatic Scala way to come a list of Eithers into a Left or Right depending on the lists content

I have a list of Eithers
val list: List[Either[String, Int]] = List(Right(5), Left("abc"), Right(42))
As a result I want a Right if everything in the list is a Right else I want a Left. This sounds like the list should be biased (e.g. use Try instead) but let's assume it isn't or shouldn't be.
The content of the resulting Right or Left will always be the same (e.g. a string, see blow) - only the Container shall differ. E.g. with the list above we want to create a string from this list so the result should be of a Left like Left("Right(5) -> Left(abc) -> Right(42)"). If we had another Right(12) instead of the Left("abc") it should be Right("Right(5) -> Right(12) -> Right(42)").
I could manually check if there is at least one Left in the list and branch with an if to create a Left or a Right as result, but I wonder: is there a more Scala-like way to do it?
You can achieve that in a functional way with a foldLeft.
Basically in the fold function you fold using the rules
Right + Right => Right
SomethingElse => Left
In scala code:
def string(a: Any, b: Any): String = if (a.toString.isEmpty)
s"${b.toString}" else s"${a.toString} -> ${b.toString}"
def transform[T, U](list: List[Either[T, U]]) =
list.foldLeft[Either[String, String]](Right("")) {
case (Right(a), bb # Right(b)) => Right(string(a, bb))
case (Right(a), bb) => Left(string(a, bb))
case (Left(a), bb) => Left(string(a, bb))
}
transform(List(Right(5), Left("abc"), Right(42)))
// prints Left(Right(5) -> Left(abc) -> Right(42))
transform(List(Right(5), Right("abc"), Right(42)))
// prints Right(Right(5) -> Right(abc) -> Right(42))
Either is actually used in sence of Value or Error in Haskell.
But scala Either's design does not allow it's use as "Error Monad". That was fixed in scalaz library via \/ type. Thing you want to basically implemented via sequence extension of Traverse types.
So prefix your code with:
import scalaz._
import Scalaz._
and get your result like
type Error[A] = String \/ A
val mlist = (list map \/.fromEither).sequence[Error, Int]
or even oneline type currying:
val mlist = (list map \/.fromEither).sequence[({type E[A] = String \/ A})#E, Int]

How should I implement a Cayley Table in Haskell?

I'm interested in generalizing some computational tools to use a Cayley Table, meaning a lookup table based multiplication operation.
I could create a minimal implementation as follows :
date CayleyTable = CayleyTable {
ct_name :: ByteString,
ct_products :: V.Vector (V.Vector Int)
} deriving (Read, Show)
instance Eq (CayleyTable) where
(==) a b = ct_name a == ct_name b
data CTElement = CTElement {
ct_cayleytable :: CayleyTable,
ct_index :: !Int
}
instance Eq (CTElement) where
(==) a b = assert (ct_cayleytable a == ct_cayleytable b) $
ct_index a == ct_index b
instance Show (CTElement) where
show = ("CTElement" ++) . show . ctp_index
a **** b = assert (ct_cayleytable a == ct_cayleytable b) $
((ct_cayleytable a) ! a) ! b
There are however numerous problems with this approach, starting with the run time type checking via ByteString comparisons, but including the fact that read cannot be made to work correctly. Any idea how I should do this correctly?
I could imagine creating a family of newtypes CTElement1, CTElement2, etc. for Int with a CTElement typeclass that provides the multiplication and verifies their type consistency, except when doing IO.
Ideally, there might be some trick for passing around only one copy of this ct_cayleytable pointer too, perhaps using an implicit parameter like ?cayleytable, but this doesn't play nicely with multiple incompatible Cayley tables and gets generally obnoxious.
Also, I've gathered that an index into a vector can be viewed as a comonad. Is there any nice comonad instance for vector or whatever that might help smooth out this sort of type checking, even if ultimately doing it at runtime?
You thing you need to realize is that Haskell's type checker only checks types. So your CaleyTable needs to be a class.
class CaleyGroup g where
caleyTable :: g -> CaleyTable
... -- Any operations you cannot implement soley by knowing the caley table
data CayleyTable = CayleyTable {
...
} deriving (Read, Show)
If the caleyTable isn't known at compile time you have to use rank-2 types. Since the complier needs to enforce the invariant that the CaleyTable exists, when your code uses it.
manipWithCaleyTable :: Integral i => CaleyTable -> i -> (forall g. CaleyGroup g => g -> g) -> a
can be implemented for example. It allows you to perform group operations on the CaleyTable. It works by combining i and CaleyTable to make a new type it passes to its third argument.

Resources