Having `f =` move to either => or ⇒ - scala

I edit a lot of Scala code in Vim, which means I hit f = a lot, as I head to the RHS of a case statement (or whatever else):
case PatternMatch(a, b, c) => RHS Here
But Scala supports unicode characters, which means that a lot of people will use ⇒ instead of => and that makes f ... a pain in the butt. Does anyone know how if there's a way to make f = move to the next = or ⇒, whichever comes first?

Try adding this to your vimrc:
nmap f= :call search('=\\|⇒')<CR>
That will alias (map) f= to a call to the search function that will jump to the next = or ⇒.

bundacia's answer is the one you asked for. Another option is to use digraphs. You can type ⇒ in vim by typing <C-k>=> in insert mode. You can also use this digraph with the f command (e.g. f<C-k>=>). No need for mappings etc. though it may be somewhat inconvenient to type.
I prefer this solution since it preserves other operator pending commands such as df=, cf=, etc. and allows the use of F, t, etc.

Related

What does `Control.refine` do in Ltac2?

I'm learning Ltac2 and reading the official documentation of coq 8.13.2.
I do not get what role Control.refine play in the evaluation inside of quotations, as there doesn't seem to be a lot of explanations to this function.
For example, using variables in tactic expressions inside a constr quotation should be done by: constr:(... $x ...), where $x is the syntactic sugar of ltac2:(Control.refine (fun () => x)).
Why does, say simply, ltac2:(x) not work? (and it indeed doesn't, as coq gives an error of Error: Cannot infer an existential variable of type ..., at the position where the constr represented by x should be inserted).
So my questions are:
What does Control.refine do in general?
It seems to be an idiom to sometimes do this: constr:( ... ltac2:(Control.refine (fun () => ...) ...), in what situation where such anti-quotation idiom should (or shouldn't) be used?
Thanks.
The ltac2:(...) in-term quotation expects an Ltac2 term of type unit, not of type constr. Actually, your example should trigger a warning because of this.
Since the content of the quotation has type unit, it means that it can only act through side-effects. The warning tells you that the value returned by the quotation will be discarded. In particular, it cannot be used to fill the hole.
Rather, the semantics of the quotation is to evaluate its content inside a goal Γ ⊢ A where Γ is the current list of hypotheses, and A the inferred type of the hole. It is expected that doing this will solve the goal, and the resulting partial proof will be used as the Coq term filler for that hole. This is precisely the rôle of Control.refine : (unit -> constr) -> unit. It takes a (for technical reasons, thunked) term as an argument and uses it to solve the goal(s) under focus.
What happens in your example is that you provide a term that is just ignored, the goal is left untouched and the quotation rightfully complains that it was not solved.
Regarding your second point, I cannot really tell. It depends on what you want do do. But in general, if you stick to antiquotations $x I would consider this more readable. It is not always possible to do so, though, e.g. if the term being built depends on a context introduced in the constr:(...) quotation.

Chaining methods left to right in Haskell (as opposed to right to left)

I come from Scala. So I frequently do stuff like:
println((1 to 10).filter(_ < 3).map(x => x*x))
In Haskell, after I discovered I can get rid of all the nested parenthesis using $ and ., I recently found myself writing:
putStrLn . show . map (**2) . filter (< 3) $ [1..10]
Now, this works, but the code reads right-to-left, and unless I shift to Arabic, this is difficult for me to reason about.
Is there any other trick that makes me chain the functions from left to right? Or this is just the Haskell idiomatic way?
Unfortunately, it's the Haskell idiomatic way. But the & operator might do what you want.
import Data.Function ((&))
[1..10] & filter (< 3) & map (**2) & show & putStrLn
Essentially, (&) = flip ($). Likewise, Control.Arrow.(>>>) = flip (.)
UPDATE (6+ months later): I have to admit, this issue is a big source of frustration for me and I have been toying with this potential solution:
https://gist.github.com/obadz/9f322df8ba6c8a9767683d2f86af8589#file-directionalops-hs-L81
Yes, it is idiomatic Haskell. Not Arabic, but rather Mathematic, derived from the syntax for composition. See also Haskell composition (.) vs F#'s pipe forward operator (|>).
Still, even in Haskell you sometimes prefer to write your calls in the other direction, and you'll find a few libraries (e.g. Data.Function since base 4.8.0) who have defined
(&) = flip ($)
so that you can express your call as
[1..10] & filter (< 3) & map (**2) & show & putStrLn
Why not make a new operator?
(#) :: a -> (a -> b) -> b
(#) = flip id
Now you can just write
[1..10] # filter (< 3) # map (**2) # show # putStrLn
This is the equivalent of the (&) operator from Data.Function.

Using match with user defined types in PL Racket

The following PL code does not work under #lang pl:
Edited code according to Alexis Kings answer
(define-type BINTREE
[Leaf Number]
[Node BINTREE BINTREE])
(: retrieve-leaf : BINTREE -> Number)
(define (retrieve-leaf btree)
(match btree
[(Leaf number) number])
What i'd like to achieve is as follows:
Receive a BINTREE as input
Check whether the tree is simply a leaf
Return the leaf numerical value
This might be a basic question but how would I go about solving this?
EDIT: The above seems to work if cases is used instead of match.
Why is that?
As you've discovered, match and cases are two similar but separate
things. The first is used for general Racket values, and the second is
used for things that you defined with define-type. Unfortunately,
they don't mix well in either direction, so if you have a defined type
then you need to use cases.
As for the reason for that, it's kind of complicated... One thing is
that the pl language was made well before match was powerful enough
to deal with arbitrary values conveniently. It does now, but it cannot
be easily tweaked to do what cases does: the idea behind define-type
is to make programming simple by making it mandatory to use just
cases for such values --- there are no field accessors, no predicates
for the variants (just for the whole type), and certainly no mutation.
Still, it is possible to do anything you need with just cases. If you
read around, the core idea is to mimic disjoint union types in HM
languages like ML and Haskell, and with only cases pattern matching
available, many functions are easy to start since there's a single way
to deal with them.
match and Typed Racket got closer to being able to do these things,
but it's still not really powerful enough to do all of that --- which is
why cases will stay separate from match in the near future.
As a side note, this is in contrast to what I want --- I know that this
is often a point of confusion, so I'd love to have just match used
throughout. Maybe I'll break at some point and hack things so that
cases is also called match, and the contents of the branches would
be used to guess if you really need the real match or the cases
version. But that would really be a crude hack.
I think you're on the right track, but your match syntax isn't correct. It should look like this:
(: retrieve-leaf : BINTREE -> Number)
(define (retrieve-leaf btree)
(match btree
[(Leaf number) number]))
The match pattern clauses must be inside the match form. Additionally, number is just a binding, not a procedure, so it doesn't need to be in parens.

Purely functional data structures for text editors

What would be good purely functional data structures for text editors? I want to be able to insert single characters into the text and delete single characters from the text with acceptable efficiency, and I would like to be able to hold on to old versions, so I can undo changes with ease.
Should I just use a list of strings and reuse the lines that don't change from version to version?
I don't know whether this suggestion is "good" for sophisticated definitions of "good", but it's easy and fun. I often set an exercise to write the core of a text editor in Haskell, linking with rendering code that I provide. The data model is as follows.
First, I define what it is to be a cursor inside a list of x-elements, where the information available at the cursor has some type m. (The x will turn out to be Char or String.)
type Cursor x m = (Bwd x, m, [x])
This Bwd thing is just the backward "snoc-lists". I want to keep strong spatial intuitions, so I turn things around in my code, not in my head. The idea is that the stuff nearest the cursor is the most easily accessible. That's the spirit of The Zipper.
data Bwd x = B0 | Bwd x :< x deriving (Show, Eq)
I provide a gratuitous singleton type to act as a readable marker for the cursor...
data Here = Here deriving Show
...and I can thus say what it is to be somewhere in a String
type StringCursor = Cursor Char Here
Now, to represent a buffer of multiple lines, we need Strings above and below the line with the cursor, and a StringCursor in the middle, for the line we're currently editing.
type TextCursor = Cursor String StringCursor
This TextCursor type is all I use to represent the state of the edit buffer. It's a two layer zipper. I provide the students with code to render a viewport on the text in an ANSI-escape-enabled shell window, ensuring that the viewport contains the cursor. All they have to do is implement the code that updates the TextCursor in response to keystrokes.
handleKey :: Key -> TextCursor -> Maybe (Damage, TextCursor)
where handleKey should return Nothing if the keystroke is meaningless, but otherwise deliver Just an updated TextCursor and a "damage report", the latter being one of
data Damage
= NoChange -- use this if nothing at all happened
| PointChanged -- use this if you moved the cursor but kept the text
| LineChanged -- use this if you changed text only on the current line
| LotsChanged -- use this if you changed text off the current line
deriving (Show, Eq, Ord)
(If you're wondering what the difference is between returning Nothing and returning Just (NoChange, ...), consider whether you also want the editor to go beep.) The damage report tells the renderer how much work it needs to do to bring the displayed image up to date.
The Key type just gives a readable dataype representation to the possible keystrokes, abstracting away from the raw ANSI escape sequences. It's unremarkable.
I provide the students with a big clue about to go up and down with this data model by offering these pieces of kit:
deactivate :: Cursor x Here -> (Int, [x])
deactivate c = outward 0 c where
outward i (B0, Here, xs) = (i, xs)
outward i (xz :< x, Here, xs) = outward (i + 1) (xz, Here, x : xs)
The deactivate function is used to shift focus out of a Cursor, giving you an ordinary list, but telling you where the cursor was. The corresponding activate function attempts to place the cursor at a given position in a list:
activate :: (Int, [x]) -> Cursor x Here
activate (i, xs) = inward i (B0, Here, xs) where
inward _ c#(_, Here, []) = c -- we can go no further
inward 0 c = c -- we should go no further
inward i (xz, Here, x : xs) = inward (i - 1) (xz :< x, Here, xs) -- and on!
I offer the students a deliberately incorrect and incomplete definition of handleKey
handleKey :: Key -> TextCursor -> Maybe (Damage, TextCursor)
handleKey (CharKey c) (sz,
(cz, Here, cs),
ss)
= Just (LineChanged, (sz,
(cz, Here, c : cs),
ss))
handleKey _ _ = Nothing
which just handles ordinary character keystrokes but makes the text come out backwards. It's easy to see that the character c appears right of Here. I invite them to fix the bug and add functionality for the arrow keys, backspace, delete, return, and so on.
It may not be the most efficient representation ever, but it's purely functional and enables the code to conform concretely to our spatial intuitions about the text that's being edited.
A Vector[Vector[Char]] would probably be a good bet. It is an IndexedSeq so has decent update / prepend / update performance, unlike the List you mention. If you look at Performance Characteristics, it's the only immutable collection mentioned that has effective constant-time update.
We use a text zipper in Yi, a serious text editor implementation in Haskell.
The implementation of the immutable state types is described in the following,
http://publications.lib.chalmers.se/records/fulltext/local_94979.pdf
http://publications.lib.chalmers.se/records/fulltext/local_72549.pdf
and other papers.
Fingertrees
Ropes
scala.collection.immutable.IndexSeq
I'd suggest to use zippers in combination with Data.Sequence.Seq which is based on finger trees. So you could represent the current state as
data Cursor = Cursor { upLines :: Seq Line
, curLine :: CurLine
, downLines :: Seq Line }
This gives you O(1) complexity for moving cursor up/down a single line, and since splitAt and (><) (union) have both O(log(min(n1,n2))) complexity, you'll get O(log(L)) complexity for skipping L lines up/down.
You could have a similar zipper structure for CurLine to keep a sequence of character before, at and after the cursor.
Line could be something space-efficient, such as ByteString.
I've implemented a zipper for this purpose for my vty-ui library. You can take a look here:
https://github.com/jtdaugherty/vty-ui/blob/master/src/Graphics/Vty/Widgets/TextZipper.hs
The Clojure community is looking at RRB Trees (Relaxed Radix Balanced) as a persistent data strcuture for vectors of data that can be efficiently concatenated / sliced / inserted etc.
It allows concatenation, insert-at-index and split operations in O(log N) time.
I imagine a RRB Tree specialised for character data would be perfectly suited for large "editable" text data structures.
The possibilities that spring to mind are:
The "Text" type with a numerical index. It keeps text in a linked list of buffers (internal representation is UTF16), so while in theory its computational complexity is usually that of a linked list (e.g. indexing is O(n)), in practice its so much faster than a conventional linked list that you could probably just forget about the impact of n unless you are storing the whole of Wikipedia in your buffer. Try some experiments on 1 million character text to see if I'm right (something I haven't actually done, BTW).
A text zipper: store the text after the cursor in one text element, and the text before the cursor in another. To move the cursor transfer text from one side to the other.

Triple colon Scala

I'm trying to pick up some scala. Reading through examples I came across this impossible-to-google nugget:
case 3 => l ::: List(3)
What does the triple colon accomplish?
Concatenates two lists - javadoc
To add to gkamal's answer, it's important to understand that methods whose names end in a colon are right-associative. So writing l ::: List(3) is the same as writing List(3).:::(l). In this case it doesn't matter since both operands are lists, but in general you'll need this knowledge to find such methods in the scaladocs.
It also helps to know that the scaladocs have a comprehensive index of all methods (and classes, etc) with symbolic names. You can reach it by clicking on the # in the upper-left corner.