I've prepared an ABP model in Promela modeling language. But I'd need some help with rewriting it in another modelling language - mCRL. I do not have any experience in it. Could someone, please, show me a way to start, or point me to good tutorial for mCRL ?
Anyway, is there a difference in code between mCRL and mCRL2 ?
my code in promela:
mtype = { msg, ack }
chan to_sender = [2] of { mtype, bit };
chan to_recvr = [2] of { mtype, bit };
active proctype Sender()
{
bit s_out=0, s_in;
do
:: to_recvr!msg,s_out ->
if
:: to_sender?ack,s_in ->
if
:: s_in == s_out ->
end: s_out = !s_out
:: else ->
skip
fi
:: timeout
fi
od
}
active proctype Receiver()
{
bit s_in, s_exp = 0;
do
:: to_recvr?msg,s_in ->
to_sender!ack,s_in;
if
:: s_in == s_exp ->
end: s_exp = !s_exp
:: else ->
skip
fi
:: to_recvr?msg,s_in -> skip
od
}
mCRL is not actively supported anymore. I think it does not even compile with the newest GCC.
There is actually an example ABP model in the mCRL2 sources: https://svn.win.tue.nl/repos/MCRL2/trunk/examples/academic/abp/abp.mcrl2.
Related
playerInstruction :: [String] -> Int -> [String]
playerInstruction mapList count = do
if count == 0
then printf "First direction : "
else printf "Next direction : "
inp <- getLine
case inp of
"Up" -> instructionProc mapList Up
"Down" -> instructionProc mapList Down
"Left" -> instructionProc mapList Leftx
"Right" -> instructionProc mapList Rightx
otherwise -> playerInstruction mapList count
This is a part of the code of a project I am working on. This is a function to take in the player's instruction and redirect the player to another function. mapList is a list of String which supposed to contain the changes of the map step by step. count is the variable to count the number of instructions the player has input. The problem I am encountering is that the compiler is saying the line
inp <- getLine
having an error. With a message as stated in the topic. I am not sure how to fix this problem. Please feel free to see this link: Haskell IO: Reading the whole text file if you want to know more about this project. Thank you.
You need to declare the function as IO in the signature:
playerInstruction :: [String] -> Int -> IO [String]
Let's say I have the following data structure and functions:
data Settings = Settings { dbName :: String } deriving Show
-- username to user id lookup
getUserId :: Settings -> String -> Int
getUserId settings username = 1
-- checks permission for a given user id
hasPermission :: Settings -> Int -> Bool
hasPermission settings userId = True
I'd like to be able to chain getUserId and hasPermission with some syntactic sugar without having to carry instance of Settings as I chain the function calls. Something like this:
main = do
let _permission = Settings{dbName="prod"} >>= getUserId "bob" >> hasPermission
print _permission
This (obviously) does not work.
Any go-to patterns for this this?
The simplest way to address such concerns is, in my opinion, to use partial application, like this:
main = do
let settings = Settings { dbName="prod" }
let getUserId' = getUserId settings
let hasPermission' = hasPermission settings
let _permission = hasPermission' $ getUserId' "bob"
print _permission
If you put the 'common' argument last, however, you can also use the built-in reader monad instance:
main :: IO ()
main = do
let getPermission = (flip getUserId) "bob" >>= (flip hasPermission)
print $ getPermission $ Settings { dbName="prod" }
Here getPermission is a local function with the type Settings -> Bool. Typically, I consider the first option (partial application) to be simpler and easier to understand.
There is a feature called implicit parameters, which has somewhat gone out of style lately, but I believe it is still supported, which offers a nice solution for this.
{-# LANGUAGE ImplicitParams #-}
data Settings = Settings { dbName :: String } deriving Show
getUserId :: (?settings :: Settings) => String -> Int
getUserId username = 1
hasPermission :: (?settings :: Settings) => Int -> Bool
hasPermission userId = True
main = do
let ?settings = Settings { dbName = "prod" }
print $ hasPermission (getUserId "bob")
See also the implicit configurations paper, which explores this problem in quite some depth, and its corresponding library, reflection.
I currently have a working parser in megaparsec, where I build an AST for my program. I now want to do some weeding operations on my AST, while being able to use the same kind of pretty errors as the parser. While this stage is after parsing, I'm wondering if there are general practices for megaparsec in doing so. Is there a way for me to extract every line and comment (used in the bundle) and add it to each item in my AST? Is there any other way that people tackle this problem?
Apologies in advance if this sounds open ended, but I'm mainly wondering is there are some better ideas than getting the line numbers and creating bundles myself. I'm still new to haskell so I haven't been able to navigate properly through all the source code.
This was answered by the megaparsec developer here.
To summarize, parsers have a getOffset function that returns the current char index. You can use that along with an initial PosState to create an error bundle which you can later pretty print.
I have a sample project within the github thread, and pasted again here:
module TestParser where
import Data.List.NonEmpty as NonEmpty
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import Data.Void
import Parser
import Text.Megaparsec
data Sample
= Test Int
String
| TestBlock [Sample]
| TestBlank
deriving (Show, Eq)
sampleParser :: Parser Sample
sampleParser = do
l <- many testParser
return $ f l
where
f [] = TestBlank
f [s] = s
f p = TestBlock p
testParser :: Parser Sample
testParser = do
offset <- getOffset
test <- symbol "test"
return $ Test offset test
fullTestParser :: Parser Sample
fullTestParser = baseParser testParser
testParse :: String -> Maybe (ParseErrorBundle String Void)
testParse input =
case parse (baseParser sampleParser) "" input of
Left e -> Just e
Right x -> do
(offset, msg) <- testVerify x
let initialState =
PosState
{ pstateInput = input
, pstateOffset = 0
, pstateSourcePos = initialPos ""
, pstateTabWidth = defaultTabWidth
, pstateLinePrefix = ""
}
let errorBundle =
ParseErrorBundle
{ bundleErrors = NonEmpty.fromList [TrivialError offset Nothing Set.empty]
-- ^ A collection of 'ParseError's that is sorted by parse error offsets
, bundlePosState = initialState
-- ^ State that is used for line\/column calculation
}
return errorBundle
-- Sample verify; throw an error on the second test key
testVerify :: Sample -> Maybe (Int, String)
testVerify tree =
case tree of
TestBlock [_, Test a _, _] -> Just (a, "Bad")
_ -> Nothing
testMain :: IO ()
testMain = do
testExample "test test test"
putStrLn "Done"
testExample :: String -> IO ()
testExample input =
case testParse input of
Just error -> putStrLn (errorBundlePretty error)
Nothing -> putStrLn "pass"
Some parts are from other files, but the important parts are in the code.
Hi i have a very noob question, lets say i want to create a game when you have to answer questions, i wrote this
data Question = Question { answer::String, text::String }
data Player = Player { name::String, points::String }
answerQuestion :: Question -> Player -> Player
answerQuestion question player
| isCorrect question playerAnswer = Player (name player) (points player + 1)
| otherwise = player
where
playerAnswer = do
putStrLn text(question)
getLine
isCorrect :: Question -> String -> Bool
isCorrect question try = try == answer(question)
now playerAnswer has type IO String so do i have to call isCorrect inside the do block ? Is there another way to parse IO String into String ?
In case of first i am feeling like loosing all the benefits from functional programming because i will end up writing my entire code in do blocks in order to access the String value
Note: This post is written in literate Haskell. You can save it as Game.lhs and try it in your GHCi.
now playerAnswer has type IO String so do i have to call isCorrect inside the do block?
Yes, if you stay on that course.
Is there another way to parse IO String into String?
None that's not unsafe. An IO String is something that gives you a String, but whatever uses the String has to stay in IO.
In case of first i am feeling like loosing all the benefits from functional programming because i will end up writing my entire code in do blocks in order to access the String value .
This can happen if you don't take measurements early. However, let's approach this from a top-down approach. First, let's introduce some type aliases so that it's clear whether we look at a String in as an answer or a name:
> type Text = String
> type Answer = String
> type Name = String
> type Points = Int -- points are usually integers
Your original types stay the same:
> data Question = Question { answer :: Answer
> , text :: Text } deriving Show
> data Player = Player { name :: Name
> , points :: Points } deriving Show
Now let's think about a single turn of the game. You want to ask the player a question, get his answer, and if he's right, add some points:
> gameTurn :: Question -> Player -> IO Player
> gameTurn q p = do
> askQuestion q
> a <- getAnswer
> increasePointsIfCorrect q p a
This will be enough to fill your game with a single turn. Let's fill those functions with life. askQuestions and getAnswer change the world: they print something on the terminal and ask for user input. They have to be in IO at some point:
> askQuestion :: Question -> IO ()
> askQuestion q = putStrLn (text q)
> getAnswer :: IO String
> getAnswer = getLine
Before we actually define increasePointsIfCorrect, let's think about a version that does not use IO, again, in a slightly more abstract way:
> increasePointsIfCorrect' :: Question -> Player -> Answer -> Player
> increasePointsIfCorrect' q p a =
> if isCorrect q a
> then increasePoints p
> else p
By the way, if you watch closely, you'll notice that increasePointsIfCorrect' is actually a single game turn. After all, it's checks the answer and increases the points. Speaking of:
> increasePoints :: Player -> Player
> increasePoints (Player n p) = Player n (p + 1)
> isCorrect :: Question -> Answer -> Bool
> isCorrect q a = answer q == a
We now defined several functions that don't use IO. All that's missing is increasePointsIfCorrect:
> increasePointsIfCorrect :: Question -> Player -> Answer -> IO Player
> increasePointsIfCorrect q p a = return (increasePointsIfCorrect' q p a)
You can check this now with a simple short game:
> theQuestion = Question { text = "What is your favourite programming language?"
> , answer = "Haskell (soon)"}
> thePlayer = Player { name = "Alberto Pellizzon"
> , points = 306 }
>
> main :: IO ()
> main = gameTurn theQuestion thePlayer >>= print
There are other ways to handle this, but I guess this is one of the easier ones for beginners.
Either way, what's nice is that we could now test all the logic without using IO. For example:
prop_increasesPointsOnCorrectAnswer q p =
increasePointsIfCorrect' q p (answer q) === increasePoints p
prop_doesnChangePointsOnWrongAnswer q p a = a /= answer q ==>
increasePointsIfCorrect' q p a === p
ghci> quickCheck prop_increasesPointsOnCorrectAnswer
OK. Passed 100 tests.
ghci> quickCheck prop_doesnChangePointsOnWrongAnswer
OK. Passed 100 tests.
Implementing those tests completely is out of scope of this question though.
Exercises
Tell the player whether his answer was correct.
Add playGame :: [Question] -> Player -> IO (), which asks several questions after another and tells the player the final score.
Ask the player for his/her name and store it in the initial player.
(Very Hard for a beginner) Try to find a way so that you can either play a game automatically (for example for testing), or "against" a human. Hint: Look for "domain specific language".
as an alternative you can promote answerQuestion to an action as well:
answerQuestion :: Question -> Player -> IO Player
answerQuestion question player =
answer <- playerAnswer
if isCorrect question answer
then return $ Player (name player) (points player + 1)
else return player
where
playerAnswer = do
putStrLn $ text question
getLine
so yes you could say that in this case you should call isCorrect from inside a do block
Is there another way to parse IO String into String?
No, there is no safe way of turning IO String into String. This is the point of the IO type!
now playerAnswer has type IO String so do i have to call isCorrect inside the do block ? [...] In case of first i am feeling like loosing all the benefits from functional programming because i will end up writing my entire code in do blocks in order to access the String value
That's what it looks like at first, but it's not like that. The trick is that we use adapter functions to connect the pure and the effectful worlds. So for example, suppose you have:
A question question :: IO Question
An answer answer :: IO String
And you want to call isCorrect :: Question -> String -> Bool on the Question and the String. One way to do this is to use the liftA2 function:
import Control.Applicative (liftA2)
example :: IO Bool
example = liftA2 isCorrect question answer
where question :: IO Question
question = _
answer :: IO String
answer = _
liftA2 has this generic type:
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
In this example, we're using it with:
f := IO
a := Question
b := String
c := Bool
So what liftA2 does is adapt a pure function to work with side-effecting types. And that's how Haskell programming generally works:
You try to write most of your code as pure functions
You use auxiliary functions like liftA2 to adapt them to work with impure effects.
It takes some study and practice to get the hang of this.
I used llvm-general-pure to build an abstract syntax trees for a program in the LLVM language.
Using the provided pretty printer, I get output that looks like
A.Module {
A.moduleName = "main",
A.moduleDataLayout = Nothing,
A.moduleTargetTriple = Nothing,
A.moduleDefinitions = [
...
A.GlobalDefinition A.G.Function {
A.G.linkage = A.L.External,
A.G.visibility = A.V.Default,
A.G.callingConvention = A.CC.C,
A.G.returnAttributes = [],
A.G.returnType = A.IntegerType {A.typeBits = 32},
A.G.name = A.Name "Main",
A.G.parameters = ([], False),
A.G.functionAttributes = [],
A.G.section = Nothing,
A.G.alignment = 0,
A.G.garbageCollectorName = Nothing,
A.G.basicBlocks = [
A.G.BasicBlock (A.Name "mainBlock") [
A.Name "n57" A.:= A.Alloca {
A.allocatedType = A.IntegerType {A.typeBits = 64},
A.numElements = Nothing,
A.alignment = 0,
A.metadata = []
},
...
I want output that looks like
define i32 #main() {
mainBlock:
%n57 = alloca i64
...
}
...
It looks suspiciously like there's an automatically generated parser for the LLVM language in the llvm-general-quote package, but no corresponding pretty printer.
Stephen Diehl's excellent article hints at something called moduleString.
llvm-general-pure doesn't have a pure pretty printer, we have to go through llvm-general to do this. It can print out the IR by going through withModuleFromAST on the Haskell AST to manifest the Module representation (i.e. the C++ Module) of the IR and then calling moduleLLVMAssembly to invoke the pretty printer.
moduleLLVMAssembly :: Mod.Module -> IO String
withModuleFromAST :: Context -> AST.Module -> (Mod.Module -> IO a) -> ErrorT String IO a
This isn't pure Haskell though, it's all going through the FFI to call LLVM's internal functions.
import LLVM.General.Module as Mod
import qualified LLVM.General.AST as AST
ppModule :: AST.Module -> IO ()
ppModule ast = withContext $ \ctx ->
runExceptT $ withModuleFromAST ctx ast $ \m -> do
llstr <- moduleLLVMAssembly m
putStrLn llstr
There's no reason we couldn't have a pure pretty printer though and indeed I started on a project to do just this called llvm-pp, but it's just a large amount of mind-numbingly boring work to write a pretty printer for the whole LLVM specification.