OCaml special characters formatting? - ocaml

I have the following ocaml code:
let rec c_write =
"printf(\" %d \");\n"
On calling this function in the interpreter, I expect to get the output
printf("%d"); followed by a new line, but instead I get
printf(\" %d \");\n
How can I get my expected output when I'm calling the function without using any other I/O functions?

The expression let rec c_write = "printf(\" %d \");\n" is not a function. It is a value of type string which is bound to a variable named c_write. So you're not using any I/O functions in your code.
When entered in the interactive toplevel, this value is printed by the interpreter evaluation loop for user convenience. The same as when a Python interpreter will print for you the value that you've just entered.
The representation, chosen by the OCaml toplevel interpreter, in general, has nothing to do with the representation which is used to store a value in a file or to print it. Moreover, in OCaml, there is no canonical representations.
If you want to write a function that prints a C printf statement then this is how it will look like in OCaml
let print_printf () =
print_endline {|printf("%d");|}
In the example above, I've used {||} to denote a sting literal instead of more common "", since in this literal there is no need to escape special characters and they are interpreted literally (i.e., the don't have any special meaning).
You can achieve the same result using the regular "" quotes for denoting it
let print_printf () =
print_endline "printf(\"%d\");"
Here is an example of the toplevel interaction using these definitions:
# let print_printf () =
print_endline {|printf("%d");|};;
val print_printf : unit -> unit = <fun>
# print_printf ();;
printf("%d");
- : unit = ()
# let print_printf () =
print_endline "printf(\"%d\");";;
val print_printf : unit -> unit = <fun>
# print_printf ();;
printf("%d");
- : unit = ()
If you will put this code in a file, compile, and execute and redirect into a C file it will be a well-formed C file (modulo the absence of the function body).

Since you are somehow using the toplevel printer for printing, and that you somehow needs a very specific format, you need to install a custom printer.
The following would work:
# #install_printer Format.pp_print_string;;
# " This \" is not escaped " ;;
- : string = This " is not escaped
However, it seems very likely that this is not really the problem that you are trying to solve.

Related

Haskell - Saving string input into a list

I'm a Haskell beginner and I am doing a small file for a project that should take the input of interaction data for groups of two people and save it to a list to be output at the end. I have done my best to implement this but it seems like the program hits the "stop" case no matter what is input. Any help or advice would be appreciated.
import Data.List
import Text.Read
main :: IO ()
main = do
putStrLn "This program is a means to record interactions between individuals during the COVID-19 pandemic."
putStrLn "Please enter your interactions in this format: 'x interacted with y'"
inputs <- getUserInputs
putStr "input: "
putStrLn ("list sequence " ++ show (inputs))
parseInput :: String -> Maybe String
parseInput input = if input == "stop" then Nothing else (readMaybe input):: Maybe String
getUserInputs :: IO [String]
getUserInputs = do
input <- getLine
case parseInput input of
Nothing -> return []
Just aString -> do
moreinputs <- getUserInputs
return (aString : moreinputs)
Show and Read are intended to produce and consume the representation of a value as a Haskell expression. That’s why when you call show on a String, it produces a quoted string:
> show "beans"
"\"beans\""
Therefore Read expects the string to be quoted as well, so readMaybe is always returning Nothing in your code because you’re not supplying quotes:
> readMaybe "beans" :: Maybe String
Nothing
> readMaybe "\"beans\"" :: Maybe String
Just "beans"
Therefore the fix is simple: remove the call to readMaybe and just return the string directly:
parseInput1 :: String -> Maybe String
parseInput1 input = if input == "stop"
then Nothing
else Just input
Which, as a matter of style preference, you could also write with guards, pattern matching, or the Maybe monad instead of if:
parseInput2 input
| input == "stop" = Nothing
| otherwise = Just input
parseInput3 "stop" = Nothing
parseInput3 input = Just input
import Control.Monad (guard)
parseInput4 input = do
-- ‘guard’ returns ‘Nothing’,
-- short-circuiting the ‘do’ block,
-- if its condition is ‘False’.
guard (input /= "stop")
pure input
Read and Show are fine for simple programs, particularly when you’re learning Haskell, but in larger applications it’s helpful to use them mostly for debug input and output and reading input you’ve already validated. Parsing and pretty-printing libraries are preferable for more involved parsing and producing human-readable output, respectively; megaparsec and prettyprinter are good default choices in that area.

why the use of _ prevent having warnings

I have the following code (it's a test so it does nothing interesting)
let test k =
let rec aux = function
|0 -> 0
|z when z = 2 -> raise Exit
|_ -> aux (k-1)
in try let _ = aux k in true
with Exit -> false
At the end there is the use of the syntax : let _, to me it's just a syntax when you don't have an idea of a name you can use to define your function.
Yet if I do the following :
let test k =
let rec aux = function
|0 -> 0
|z when z = 2 -> raise Exit
|_ -> aux (k-1)
in try let b = aux k in true
with Exit -> false
I get a warning like : "variable b is unused", I don't understand why there is a difference between let _ and let b ?
For example I know that when dealing with unit type it's common to use the syntax : let (). Yet I don't have any warning when doing :
let b = print_int 2
even if I am not using :
let () = print_int 2
So what is particular with let _ ?
Thank you !
This is a convention, recognized by the compiler, to indicate that you're not going to use the result of a computation, e.g.,
let a = 5 + 6 in
()
will (or will not, depending on your warning settings) trigger the unused variable warning, since you clearly bound the result to a variable a, but not using it in the rest of your computation. In imperative languages it is quite common, to compute expressions for their side effects and ignore produced values if any. Since OCaml is a functional language, in which values are used to produce values, it usually an indicator of an error, when you forgot to use a bound variable.
Therefore, to explicitly tell the compiler that you're ignoring the value, you may start your variable with the underscore, e.g.,
let _unusued = 5 + 6 in
()
You can just use a wild pattern _ (which also starts with the underscore).
You have a warning with your second code because you define the variable b containing a value and you do not use it after.
The best use if you do not want to use the result of any expression is to discard its result using the 'let _ =' construct (it tells you want the expression to be evaluated, for potential side effects, but do not care to keep its result).
For the second part of your question, I think there are different rules related to the top loop, so the behaviours may not be comparable. In the first part, you define b inside a function and in the second part, you define b inside the top loop. In the top loop, you may define variables you will not use without getting a warning.

Explanation why a list with different types is a valid Haskell expression needed

So in an exercise I am given a list like ["xyz", True, 42]. The question was if that is a valid expression in Haskell and what the type of that expression is.
A list can only hold homogenous types but the type of "xyz"is [Char], the type of True is Bool and the type of 42 is Num p => p. That is different types so I can't put them into a list.
That's what I thought. But the given answer to that exercise is "Yes, it is a valid expression. Show-instance!."
Why is it a valid expression although the types of the list elements are different and what is meant with show-instance? I'm thinking of something like superclasses from object oriented languages but I thought this is not how Haskell works.
If we are allowed to define some more context, we can make this a valid expression, for instance with:
import Data.String(IsString(fromString))
instance IsString Bool where
fromString [] = False
fromString _ = True
instance Num Bool where
(+) = (||)
(*) = (&&)
abs = id
signum = id
fromInteger 0 = False
fromInteger _ = True
negate = not
(here I used the truthiness of Python to convert from an Integer and String literal)
Then we can write it with the OverloadedStrings pragma:
{-# LANGUAGE OverloadedStrings #-}
the_list = ["xyz", True, 42]
This will then be equivalent to:
Prelude Data.String> ["xyz", True, 42]
[True,True,True]
But note that the list still contains only Bools, we only made Bool an instance of IsString and Num to enable us to convert string literals and number literals to Bools.
A list of heterogeneous types is not possible in Haskell, and since by default a Bool is not a Num, we thus can not parse that expression without adding some extra magic.
An additional note is that it is valid Haskell grammar: syntactically there is nothing wrong, it is only in the next stage of the compiler: type checking, etc. that it will raise errors, since the syntax is nonsensical.
My lecturer gave me a hint to check for Existential types in Haskell.
I produced a working example from the description from the link above:
{-# LANGUAGE ExistentialQuantification #-}
module Main where
data Showable = forall a . Show a => MkShowable a
pack:: Show a => a -> Showable
pack a= MkShowable a
instance Show Showable where
show (MkShowable a) = show a
hlist :: [Showable]
hlist = [pack "xyz", pack True, pack 42]
main :: IO ()
main = do
putStrLn "Heterogenous list 'camouflaged' as Showable:"
print hlist
This works and produces indeed the input from the exercise. The datatype extension for Existential Quantification in the first line is necessary.
My explanation (I might have gotten something wrong though):
I create a new type Showablewith one constructor MkShowable that takes any value a as long as it is in typeclass Show and thus makes a Showable out of it.
The method pack makes a Show a become a Showable by using the constructor MkShowable I described in 1.
Showable is made an instance of Show-typeclass and tells that if a Showable(MkShowable a) is to be shown, simply show a. So we can easily print our Showables.
Furthermore I created a (heterogenous) list hlist of type [Showable]and packed the values from my example into it, using pack. The list is printed in the main function.
This really reminds me of object-oriented programming.

How can I unit test Alex code?

I'm writing a lexer in Alex with the monad wrapper. It's not behaving as I expect, and I would like to write some unit tests for it. I can write unit tests for lexing a single token by doing:
runAlex "foo" alexMonadScan `shouldBe` Right TokenFoo
but I don't know how to test that the string "foo bar" gets lexed to [TokenFoo, TokenBar].
Given that Token is my token type, I'd need a function like runAlex that has the type String -> Alex [Token] -> Either String [Token], but I don't know how to transform alexMonadScan so that it has the type Alex [Token] rather than Alex Token.
I tried
runAlex "foo bar" (liftM (:[]) alexMonadScan) `shouldBe` [TokenFoo, TokenBar]
which seems to have the right type, but it returns Right [TokenEOF], apparently dropping the tokens it saw along the way.
How can I achieve this?
There is a function alexScanTokens :: String -> [token] which you can use.
It's defined in the file templates/wrappers.hs
Here's a monadic version I found here:
alexScanTokens :: String -> Either String [Keyword]
alexScanTokens inp = runAlex inp gather
where
gather = do
t <- alexMonadScan
case trace (show t) t of
EOF -> return [EOF]
_ -> (t:) `liftM` gather

OCaml Option get

I'm new to OCaml, I'm trying to understand how you're supposed to get the value from an 'a option. According to the doc at http://ocaml-lib.sourceforge.net/doc/Option.html, there is a get function of type 'a option -> 'a that does what I want. but when I type:
# let z = Some 3;;
val z : int option = Some 3
# get z;;
Error: Unbound value get
# Option.get z;;
Error: Unbound module Option
Why isnt this working?
The traditional way to obtain the value inside any kind of constructor in OCaml is with pattern-matching. Pattern-matching is the part of OCaml that may be most different from what you have already seen in other languages, so I would recommend that you do not just write programs the way you are used to (for instance circumventing the problem with ocaml-lib) but instead try it and see if you like it.
let contents =
match z with
Some c -> c;;
Variable contents is assigned 3, but you get a warning:
Warning 8: this pattern-matching is not exhaustive. Here is an example
of a value that is not matched: None
In the general case, you won't know that the expression you want to look inside is necessarily a Some c. The reason an option type was chosen is usually that sometimes that value can be None. Here the compiler is reminding you that you are not handling one of the possible cases.
You can pattern-match “in depth” and the compiler will still check for exhaustivity. Consider this function that takes an (int option) option:
let f x =
match x with
Some (Some c) -> c
| None -> 0
;;
Here you forgot the case Some (None) and the compiler tells you so:
Warning 8: this pattern-matching is not exhaustive. Here is an example
of a value that is not matched: Some None
The usual way to do this is with pattern matching.
# let x = Some 4;;
val x : int option = Some 4
# match x with
| None -> Printf.printf "saw nothing at all\n"
| Some v -> Printf.printf "saw %d\n" v;;
saw 4
- : unit = ()
You can write your own get function (though you have to decide
what you want to do when the value is None).
You should listen to the above posters advice regarding type safety but also be aware that unsafe function such as Option.get (which is available in batteries btw) are usually suffixed with exn. If you're curious this is how Option.get or Option.get_exn could be implemented then:
let get_exn = function
| Some x -> x
| None -> raise (Invalid_argument "Option.get")