Idris REPL: creating function - read-eval-print-loop

How do I write a function in the Idris REPL ? If I type the function definition longer: string -> string -> string in the REPL, I get the following error message :
(input):1:7: error: expected: "$",
"&&", "*", "*>", "+", "++", "-",
"->", ".", "/", "/=", "::", "<",
"<$>", "<*", "<*>", "<+>", "<<",
"<=", "<==", "<|>", "=", "==",
">", ">=", ">>", ">>=", "\\\\",
"`", "|", "||", "~=~",
ambiguous use of a left-associative operator,
ambiguous use of a non-associative operator,
ambiguous use of a right-associative operator,
end of input, function argument
longer: string -> string -> string<EOF>
^

Idris documentation has example of what you need. You should use :let command. Like this:
Idris> :let longer : String -> String -> String; longer s1 s2 = if length s1 > length s2 then s1 else s2
Idris> longer "abacaba" "abracadabra"
"abracadabra" : String
By default Idris REPL doesn't do anything smart, it doesn't enter some smart multiline mode when you enter type of function. :let command is used to define any top-level bindings inside REPL.
Another moment: if you want to use string type you should use String (started with uppercase letter) instead of string.

Related

Split string in Go while preserving escaped spaces

I can split a string with strings.Split:
strings.Split(`Hello World`, " ")
// ["Hello", "World"] (length 2)
But I'd like to preserve backslash escaped spaces:
escapePreservingSplit(`Hello\ World`, " ")
// ["Hello\ World"] (length 1)
What's the recommended way to accomplish this in Go?
Since go does not support look arounds, this problem is not straightforward to solve.
This gets you close, but leaves a the trailing space intact:
re := regexp.MustCompile(`.*?[^\\]( |$)`)
split := re.FindAllString(`Hello Cruel\ World Pizza`, -1)
fmt.Printf("%#v", split)
Output:
[]string{"Hello ", "Cruel\\ World ", "Pizza"}
You could then trim all the strings in a following step.

What is {} in assignment?

In Go, when assigning multiple values to an array, braces {....} is used. What is this braces? Is it anonymous struct?
package main
import "fmt"
func main() {
var string_array [4]string = [4]string {"X", "Y", "Z", "W"}
var int_array [5]int = [5]int {1,2,3}
fmt.Println(string_array)
fmt.Println(int_array)
}
{"X", "Y", "Z", "W"} is the same as below and Go runtime is doing an implicit conversion?
type anonymous struct {
_0 string
_1 string
_2 string
_3 string
}
var anon anonymous = anonymous{"X", "Y", "Z", "W"}
Why not using ["X", "Y", "Z", "W"] if it is an array?
multiple assignment from array or slice
Go array initialization
Where in the Golang specification is this syntax explained?
It's documented in the Go language specification under "Composite literals" (emphasis mine):
Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.
Where "brace-bound" refers to the values being delimited with { and } as per your posted code.
From the grammar spec:
CompositeLit = LiteralType LiteralValue .
LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
SliceType | MapType | TypeName .
LiteralValue = "{" [ ElementList [ "," ] ] "}" . <-- This production-rule, right here
ElementList = KeyedElement { "," KeyedElement } .
KeyedElement = [ Key ":" ] Element .
Key = FieldName | Expression | LiteralValue .
FieldName = identifier .
Element = Expression | LiteralValue .

Check for differences of two sets in Elm

I am trying to check if my set of chars in elm contains only valid chars. If a char is found that is invalid, I return those chars, separated by a comma. What I currently have tries to convert the string to a list of chars, then that list to a set of chars. Then diffs the set with a set of valid chars, not sure where to go after that, I have not written much in Elm before. If no diffs are found then return nothing.
validChars : Set.Set Char
validChars =
Set.fromList <| String.toList " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
validString : String -> Maybe String
validString x =
let
list =
String.toList x
set1 =
Set.fromList list
diffs=
Set.diff set1 validChars
if Set.isEmpty diffs == True
Nothing
The if statement doesn't work in Elms online compiler, it says it is looking for "in"
Your code has a few things wrong with it, here's a version that compiles.
import Set
validChars : Set.Set Char
validChars = Set.fromList <| String.toList " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
validString : String -> Maybe String
validString string =
let
diff =
Set.diff validChars <| Set.fromList <| String.toList string
in
if not <| Set.isEmpty diff then
Just string
else
Nothing
Basically when it said it was looking for in, it wasn't wrong, in is a necessary part of a function when you use let statements.

Discriminated union type checking in F# with differernt return types

I am trying to write an interpreter in F#. I want to check the type of expressions.
Here is my discriminated union for the expressions
type Expr =
| Integer of int
| String of string
| Boolean of bool
This is the method i am using to check the types with
let checkType (e:Expr) =
match e with
| String s -> s
| Integer i -> i
| Boolean b -> b
I want the method to determine wether an expression is a string,integer or boolean.
However, visual studio gives me the following error on line 4 of the checkType method:
This expression was expected to have type string but here has type int
Am i missing something?
To expand on John Palmer's comment:
F# expects each function to have a single return type. For example, you can write a function that takes an int and returns an int, which would be a function of type int -> int. A function that parses strings into ints would be of type string -> int. And so on.
Now, what is the return type of the checkType function you've written? Since you don't specify a return type, the compiler looks at the type of the values you can return from the function -- every possible code branch must return a value, and they must all be the same type. So it looks at your match statement, sees that its first branch returns a string, and says, "Ah ha! I've figured out the return type of this function; this is a function that takes an Expr and returns a string. The function's type is Expr -> string."
Then it looks at the second branch of your match statement, and says, "Wait a minute. This is a function that returns a string, but in this code branch it's returning an int. That's not valid: the code that calls this function needs to know what type to expect it to return." And so you get the error.
Now, if you were to swap the order of your match statement cases, checking for Integer i first, then the compiler would evaluate your function as having type Expr -> int (taking an Expr input and returning an int output), and throw an error on the | String s -> s line. This time, the error would be "Wait a minute, this is a function that returns an int, so the expression s here should have been of type int. But instead, it's of type string. That's not valid."
Or delete the | String s -> s line, and you'll see an error "This expression was expected to have type int but here has type bool." Same thing: each function can have only one return type. If you want to return multiple different possible types from a function, that's what Discriminated Unions are for.
For more reading on F# types, see http://fsharpforfunandprofit.com/series/understanding-fsharp-types.html.
You can wrap all of the expressions into an Option type like Some or String:
let checkType (e:Expr) =
match e with
| String e -> "we are string: " + string e
| Integer e-> "we are integer: " + string e
| Boolean e -> "we are boolean: " + string e

New syntax for default values in Swift functions

I just noticed that the latest beta of Xcode (7.1) has changed the signature for the print function in Swift.
The new syntax is:
public func print(items: Any..., separator: String = default, terminator: String = default)
Anybody knows what this default thing is? How do you specify the default value, not just the fact that it has one?
The default in the function signature means that it has a default value and you don't have to pass a parameter.
func add(a: Int = 0, b: Int = 0) -> Int {
return a + b
}
// "normal" function call
add(2, b: 4) // 6
// no specified parameters at all
add() // 0; both a and b default to 0
// one parameter specified
// a has no external name since it is the first parameter
add(3) // 3; b defaults to 0
// b has an external name since it is not the first parameter
add(b: 4) // 4; a defaults to 0
In case of the print function separator defaults to " " and terminator to "\n".
There are 4 way to call it:
struct SomeItem {}
print(SomeItem(), SomeItem())
print(SomeItem(), SomeItem(), separator: "_")
print(SomeItem(), SomeItem(), terminator: " :) \n")
print(SomeItem(), SomeItem(), separator: "_", terminator: " :) \n")
Prints:
SomeItem() SomeItem()
SomeItem()_SomeItem()
SomeItem() SomeItem() :)
SomeItem()_SomeItem() :)
the default separator is a single space, and the default terminator is a newline
to use a different value for either of these, simply pass the desired value as an argument when you call the function - e.g.:
print("first", "second", separator: "-", terminator: "...")
print("third")
// => "first-second...third"

Resources