Is there a way to specify partial custom types in type annotations? - elm

Is there a way to specify partial custom types in type annotations?
For instance, if I have my type aliases this way: func : { a | foo : String } can I have this function:
when : Bool -> msg -> msg -> msg
when ok msgTrue msgFalse =
if ok then
msgTrue
else
msgFalse
and I would like to do something like this:
when : Bool -> (msg | NoOp) -> msg
when ok msg =
if ok then
msg
else
NoOp
where we know msg has at least NoOp value

Related

Printf arguments in OCaml

In OCaml, I obtain an error I do not understand when passing arguments which should work to Printf.printf. It is probably because I do not understand that function completely, but I cannot pin down what does not work.
First, I define a function (used for logging):
utop # let log verbosity level str =
if level <= verbosity then (
Printf.printf "\nLevel %i: " level;
Printf.printf str);;
val log : int -> int -> (unit, out_channel, unit) format -> unit = <fun>
All seems well, but then I obtain this:
utop # log 0 0 "%i" 0;;
Error: This function has type
int -> int -> (unit, out_channel, unit) format -> unit
It is applied to too many arguments; maybe you forgot a `;'.
although the following works:
utop # Printf.printf;;
- : ('a, out_channel, unit) format -> 'a = <fun>
utop # Printf.printf "%i" 0;;
0- : unit = ()
So, how can I define a function which does what log intends to do ?
Edit: Indeed, log 0 0 "%i" 0;; looks like too many arguments (4 instead of 3), but so does Printf.printf "%i" 0;; (2 instead of 1), and it works. With partial application, this gives this:
utop # Printf.printf "%i";;
- : int -> unit = <fun>
utop # log 0 0 "%i";;
Error: This expression has type (unit, unit) CamlinternalFormatBasics.precision
but an expression was expected of type
(unit, int -> 'a) CamlinternalFormatBasics.precision
Type unit is not compatible with type int -> 'a
The printf-like functions are variadic, in the sense that they accept a variable number of arguments. It is not really specific to printf and the family, you can define your own variadic functions in OCaml, this is fully supported by the type system. The only magic of printf is that the compiler translates a string literal, e.g., "foo %d to a value of type format.
Now, let's look at the type of the printf function,
('a, out_channel, unit) format -> 'a
Notice that it returns 'a which is a type variable. Since 'a could be anything it could be also a function. The ('a, out_channel, unit) format is the type of the format string that defines the type of function that is generated by this format string. It is important to understand though, that despite that "foo %d" looks like a string, in fact, it is a special built-in value of type _ format, which has a literal that looks like a string (though not all valid strings are valid literals for the _ format type.
Just to demonstrate that the first argument of printf is not a string, let's try the following,
# Printf.printf ("foo " ^ "%d");;
Line 1, characters 14-29:
1 | Printf.printf ("foo " ^ "%d");;
^^^^^^^^^^^^^^^
Error: This expression has type string but an expression was expected of type
('a, out_channel, unit) format
Now, when we know that printf is not a typical function, let's define a printf-like function ourselves. For that we need to use the kprintf-family of functions, e.g.,
# #show Printf.ksprintf;;
val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a
This function takes the function which receives the resulting string which we can log, for example,
# let log fmt = Printf.ksprintf (fun s -> print_endline ("log> "^s)) fmt;;
val log : ('a, unit, string, unit) format4 -> 'a = <fun>
# log "foo";;
log> foo
- : unit = ()
This resulting function looks more like sprintf, i.e., it will play nicely with pretty-printing function that work with string as their output devices (this is a different topic). You may find it more easier to define your logging functions, using either Printf.kfprintf or, much better, using Format.kasprintf or Format.kfprintf. The latter two functions have the following types,
val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b
val kfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
But the type of format works with the formatter type (which is an abstraction of the output device) that is the type that the pretty printers (conventionally named pp) are accepting. So the log function defined using the Format module will play better with the existing libraries.
So, using Format.kasprintf we can define your log function as,
# let log verbosity level =
Format.kasprintf (fun msg ->
if level <= verbosity then
Format.printf "Level %d: %s#\n%!" level msg);;
val log : int -> int -> ('a, Format.formatter, unit, unit) format4 -> 'a = <fun>
And here is how it could be used,
# log 0 0 "Hello, %s, %d times" "world" 3;;
Level 0: Hello, world, 3 times
- : unit = ()

Use argument passed to when in branch condition in Kotlin?

I have some code that roughly looks like this:
val myObject = myObjectRepository.findById(myObjectId);
when {
matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
else -> log.warn("No match, aborting");
}
While this works I would think that the following (which doesn't work) would be an improvement if I only need access to myObject inside the scope of when:
when(myObjectRepository.findById(myObjectId)) { myObject ->
matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
else -> log.warn("No match, aborting");
}
The error I get here is:
Unresolved reference: myObject
Can you do something like this in Kotlin and if so how? If not, is there a particular reason for why this shouldn't be allowed?
As shown in the documentation, the proper syntax would be
val myObject = myObjectRepository.findById(myObjectId);
when {
matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
else -> log.warn("myObject not found, aborting")
}
Or, to actually match what your first snippet does:
val myObject = myObjectRepository.findById(myObjectId);
when(myObject) {
null -> log.warn("myObject not found, aborting");
matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
}
You have to be careful about the syntax. In a while we use an arrow -> which has nothing to do with lambdas. I think this is what you were trying in your example.
The only valid syntax for when is this:
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
On the left side of the arrow -> you declare what the object (x) is being matched against, whereas on the right side you tell what will be executed in that case. Read about this here.
In your example you tried to chain multiple -> which does not work.
This is supported as of Kotlin 1.3. It's referred to as "Capturing when subject in a variable" and looks like this (taken from their documentation):
fun Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}

How I can pass to a function the union type without including the tag

Playing with the Elm checkboxes example. I am trying to move the following repetative code in view
, label []
[ br [] []
, input [ type' "checkbox", checked model.underline, onCheck Underline ] []
, text "underline"
]
into a separate function and use it three times. So far I have ...
makeLabel : String -> Bool -> Msg -> Html Msg
makeLabel caption bool msg =
label []
[ br [] []
, input [ type' "checkbox", checked bool, onCheck msg ] []
, text caption
]
and I would use it like
makeLabel "underline" model.underline Underline
but then I receive the following error
Function `makeLabel` is expecting the 3rd argument to be:
Msg
But it is:
Bool -> Msg
How do I pass my makeLabel function the correct action to take when a user changes the checkbox?
type Msg
= Red Bool
| Underline Bool
| Bold Bool
I don't understand how I can pass to a function the union type (Underline) without including the tag (Underline Bool)
The problem is in your type signature, rather than the code. Try this:
makeLabel : String -> Bool -> (Bool -> Msg) -> Html Msg

String to int conversion using toInt function

I am trying to convert a string to integer using String.toInt. However, when I want to bind the result to a variable and then do some simple math with it I get this error:
Function add is expecting the 2nd argument to be:
Int
But it is:
Result String Int
How can I just extract the integer part of the result?
Here's how to supply the conversion with a default value in case the parsing fails.
String.toInt "5" |> Result.toMaybe |> Maybe.withDefault 0
toInt can fail in parsing. You need to check it using a case statement:
case toInt str of
Err msg -> ... -- do something with the error message
Ok val -> ... -- val is an Int which you can add
More about Result here
The integer can also be pulled out using
Result.withDefault 0 (String.toInt "2")
You can read more about it here
According to the Elm String reference documentation, if you are extracting a number from some raw user input, you will typically want to use Result.withDefault to handle bad data in case parsing fails. You can chain this operation using pipes for cleaner code:
String.toInt "5" |> Result.withDefault 0
Maybe.withDefault 0 (String.toInt "42")
Use map:
answer = Result.map2 (+) (String.toInt "1") (String.toInt "2")
map2:
Apply a function to two results, if both results are Ok. If not, the
first argument which is an Err will propagate through.
to have the add result as a string
resultAsString r =
case r of
Err msg -> msg
Ok value -> toString value
resultAsString answer
to make things easier you can create an addStrings function:
addStrings : String -> String -> Result String Int
addStrings a b =
Result.map2 (+) (String.toInt a) (String.toInt b)
You can even get away with the Result type altogether:
addStrings : String -> String -> String
addStrings a b =
let
r =
Result.map2 (+) (String.toInt a) (String.toInt b)
in
case r of
Err msg ->
msg
Ok value ->
toString value
Testing
import Html exposing (Html, text)
main : Html msg
main =
text (addStrings "1" "2")
output 3
The withDefault method forces you to define a value that can be used for calculations but it is not always possible to establish a value that is significant for errors. Most often you need all the possible values, and default is not fit. Here I provide a result type check function you can use to decide if you use or not the converted value:
isErrorResult r =
case r of
Err msg ->
True
Ok value ->
False
You can use it like this:
r = String.toInt "20b"
if isErrorResult r then
-- not a valid Interger, abort or whatever
else
-- a good integer, extract it
a = Result.withDefault 0 r
-- and make good use of it
the default value (0 in this case) passed to withDefault is meaningless, because we made sure that r is not an Err.
You can do this as below.
---- Elm 0.19.0 ----------------------------------------------------------------
Read <https://elm-lang.org/0.19.0/repl> to learn more: exit, help, imports, etc.
--------------------------------------------------------------------------------
> parseInt string = String.toInt string
<function> : String -> Maybe Int
> resultParseInt string = \
| Result.fromMaybe ("error parsing string: " ++ string) (parseInt string)
<function> : String -> Result String Int
> resultParseInt "12"
Ok 12 : Result String Int
> resultParseInt "12ll"
Err ("error parsing string: 12ll") : Result String Int
>
I have changed guys answers a bit, since it appears to be of type Maybe
isErrorResult : String -> Bool
isErrorResult r =
case String.toInt r of
Nothing -> True
Just value -> False

OCaml - Wrong function type

I have made a class method, and I'd like to have this type :
unit -> (dir -> 'b)
But my actual method:
method iter () = fun x -> match x with
| Up -> if (Stack.is_empty pz) then raise Stack.Empty else if (Stack.length pz = 1) then failwith "Cannot go up" else (ignore (Stack.pop pz) ; {< a = (Stack.top pz) >})
| Down(v) -> match (Stack.top pz) with
| Noeud(o, {contents = []}) -> raise Not_found
| Noeud(o, {contents = l}) -> if mem_assoc v l then ((Stack.push (assoc v l) pz) ; {< a = (Stack.top pz) >} ) else raise Not_found
has the type unit -> dir -> 'b
How can I make it so it becomes the first type?
Here are the custom types :
type 'a arbre = Noeud of 'a option ref * (char * 'a arbre) list ref
type dir = Up | Down of char
Edit: I need this so it can comply to a certain interface, and because of the type mismatch, it won't compile.
Thanks!
This is not the problem. unit -> (dir -> 'b) and unit -> dir -> 'b are the same type in OCaml! (the type arrow is right-associative)
Could you show us the actual error message so we can know where the problem lies?
Addendum: have you actually tried this? If there is no other issue, then you'll find it'll just work.