Please explain this example in the Stream docs, what is [< >] syntax? - ocaml

https://ocaml.org/api/Stream.html
val from : (int -> 'a option) -> 'a t
Stream.from f returns a stream built from the function f. To create a new stream element, the function f is called with the current stream count. The user function f must return either Some <value> for a value or None to specify the end of the stream.
Do note that the indices passed to f may not start at 0 in the general case. For example, [< '0; '1; Stream.from f >] would call f the first time with count 2.
There are two things confusing me about this example.
1.
I had no luck googling for meaning of [< ... >] syntax. The closest I found was: https://ocaml.org/manual/lex.html#sss:keywords which just says those character sequences are keywords
[< ... ] seems to be used when printing, but not defining, polymorphic variants: https://ocaml.org/manual/polyvariant.html
If I paste in something like [< '0; '1; >] I get a syntax error.
So it's currently quite baffling to me what this example is purporting to show.
2.
The example says that [< '0; '1; Stream.from f >] would call f the first time with count 2
And I just wonder ... why? how? I can see that 2 follows on from '0 and '1, but how do those values influence starting value of f? (and why are they prefixed with '?)

The deprecated Stream module was built to be used with a camlp{4,5} syntactic extension that added support for the [< ...>]. See https://camlp5.github.io/doc/html/parsers.html for more documentation.
However, if you are not maintaining legacy code, you probably want to avoid the Stream module altogether and use the Seq module instead. In particular, Stream will not be part of the standard library starting with OCaml 5.0 .

Related

This expression has type processor_return_type but an expression was expected of type unit

I now have a function called processor, inside the processor function, a list will be matched to different patterns. In some patterns I wish it to return a tuple while the rest calls processor again.
Suppose I now have a custom type to wrap two types of processor:
type processor_return_type =
| REC of unit
| INFO of (string list * bool)
My processor basically looks like this:
let rec processor cmds stack env =
match (cmds, stack) with
| (ADD::rest_cmds, first_list::rest_stack) -> ... processor a b c
...
| (FUN::...) -> ... let (sl, b) = processor a b c in processor d e f
| (RETURN::...) -> (string list, a bool)
| _ -> REC()
...
in
Then I invoke this function with (you can assume I give correct arguments):
processor cmd_list [[]] [[]];;
The error emerges:
664 | processor cmd_list [[]] [[]];;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type processor_return_type
but an expression was expected of type unit
How could I fix this issue?
Thanks for including the error message and the indicated erroneous part of the code.
The expression that the compiler is complaining about is the entire call to processor. In other words, the reason the compiler is expecting something of type unit is because of the context of the call, which you unfortunately don't show.
Generally your code should expect to get a result back from the call to processor and should handle the result appropriately. If there are other branches of your code (the else part of an if, say), they have to be of the same type also.
Here's an example of an erroneous call context:
if some_test () then
Printf.printf "did not want to call processor\n"
else
proceessor ...
If you show more of the context of the call, people can give you a more helpful answer maybe.

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.

OCaml |> operator

Could someone explain what the |> operator does? This code was taken from the reference here:
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
I can see what it does, but I wouldn't know how to apply the |> operator otherwise.
For that matter, I have no idea what the Module.() syntax is doing either. An explanation on that would be nice too.
Module.(e) is equivalent to let open Module in e. It is a shorthand syntax to introduce things in scope.
The operator |> is defined in module Pervasives as let (|>) x f = f x. (In fact, it is defined as an external primitive, easier to compile. This is unimportant here.) It is the reverse application function, that makes it easier to chain successive calls. Without it, you would need to write
let m = PairsMap.(add (1,0) "world" (add (0,1) "hello" empty))
that requires more parentheses.
The |> operator looks like the | in bash.
The basic idea is that
e |> f = f e
It is a way to write your applications in the order of execution.
As an exemple you could use it (I don't particularly think you should though) to avoid lets:
12 |> fun x -> e
instead of
let x = 12 in e
For the Module.() thing, it is to use a specific function of a given module.
You probably have seen List.map before.
You could of course use open List and then only refer to the function with map. But if you also open Array afterwards, map is now referring to Array.map so you need to use List.map.
The |> operator represents reverse function application. It sounds complicated but it just means you can put the function (and maybe a few extra parameters) after the value you want to apply it to. This lets you build up something that looks like a Unix pipeline:
# let ( |> ) x f = f x;;
val ( |> ) : 'a -> ('a -> 'b) -> 'b = <fun>
# 0.0 |> sin |> exp;;
- : float = 1.
The notation Module.(expr) is used to open the module temporarily for the one expression. In other words, you can use names from the module directly in the expression, without having to prefix the module name.

Why does currying foldr with # produce an operator domain error?

So I'm writing a flatten fn, and I got it to this:
fun flatten ls = List.foldr op # [] ls
And I realized that naming the variable ls should be unnecessary, instead I could probably just paritally apply foldr. But this breaks:
val flatten = List.foldr op # []
Whats making it mess up? I seems like the typ would have to be inferred for both the fun declaration and for the partially applied foldr.
A similar sum function works, which makes me wonder why # is particularly not working:
val sum = List.foldr op + 0
Edit: the error I'm getting:
- val flatten = List.foldr op # [];
stdIn:1.6-2.13 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val flatten = fn : ?.X1 list list -> ?.X1 list
- flatten [[1], [1]];
stdIn:3.1-3.19 Error: operator and operand don't agree [literal]
operator domain: ?.X1 list list
operand: int list list
in expression:
flatten ((1 :: nil) :: (1 :: nil) :: nil)
I'm a bit unclear on what error exactly you are referring to. You mention in the headline that you are getting an "operator domain error", however you code just produces a "value restriction" warning. There is a big difference.
Value restriction is one of the more complex things to get your head around, but in essence it is there to preserve type safety when having references in the language.
The MLton wiki has a great article on value restriction, which covers Why the value restriction exists, unnecessarily rejected programs, alternatives to the value restriction and how to work with the value restriction.
AJ,
Jesper's article both explains the warning you see, and is insightful, but for a more practical solution to your problem, you might want to try this:
val flatten = foldr op # ([]:int list);
I believe that should solve your problem.
EDIT: I chose int list as the explicit type because I observed the nature of your warning message, and inferred from there, int list was what you needed. [=
Note: Above solution destroys polymorphism and restricts input to the type chosen.

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")