It looks like the keyword "in" is used as a variable - elm

Pasting the following code in http://elm-lang.org/try and clicking on "Compile" :
import Html exposing (text)
main =
let (x, y, _) = List.foldL (\elem (sum, diff, mult) ->
(sum + elem, elem - diff, mult * elem)
) (0, 0, 0) [1, 2, 3, 4, 5] in
text ("Hello, World!" ++ toString x)
results in an unexpected error:
Detected errors in 1 module.
-- SYNTAX PROBLEM ------------------------------------------------------------
It looks like the keyword in is being used as a variable.
7| ) (0, 0, 0) [1, 2, 3, 4, 5] in
^
Rename it to something else.
What is wrong here? Parentheses match.

Indentation is important in Elm, and you've got a closing parenthesis that is too far to the left (the second to last line). Changing it to this will be valid code (also, it's List.foldl, not foldL):
main =
let (x, y, _) = List.foldl (\elem (sum, diff, mult) ->
(sum + elem, elem - diff, mult * elem)
) (0, 0, 0) [1, 2, 3, 4, 5] in
text ("Hello, World!" ++ toString x)
It is probably more idiomatic to put the in statement on its own line, aligned with let, just for keeping things clear:
main =
let (x, y, _) = List.foldl (\elem (sum, diff, mult) ->
(sum + elem, elem - diff, mult * elem)
) (0, 0, 0) [1, 2, 3, 4, 5]
in
text ("Hello, World!" ++ toString x)
You could also incorporate elm-format into your editing process to automatically format your code on save.

Related

Kotlin aggregate consecutive list elements

I'd like to sum up consecutive numbers in a Kotlin list.
If the list has a 0 then it should start summing up the numbers after 0. The result would be a list of sums. Basically sum up until the first 0 then until the next 0 and so forth.
For example:
val arr = arrayOf(1, 2, 0, 2, 1, 3, 0, 4)
// list of sums = [3, 6, 4]
At the moment I got it working with fold:
val sums: List<Int> = arr.fold(listOf(0)) { sums: List<Int>, n: Int ->
if (n == 0)
sums + n
else
sums.dropLast(1) + (sums.last() + n)
}
but I wonder if there is a simpler or more efficient way of doing this.
I would personally have written it this way:
val sums = mutableListOf(0).also { acc ->
arr.forEach { if (it == 0) acc.add(0) else acc[acc.lastIndex] += it }
}
Using a mutable list, you avoid having to do any drop / concatenation. The code is also easier to follow.
You can still convert it to an immutable list using .toList() if you need to.

Remove only the trailing elements of a Vec that match a condition

I have a Vec<T> that has elements matching a pattern. I want to remove all trailing instances of the elements that match the pattern.
For example, I have a Vec<i32> and the pattern is (|x| x == 0). If the input was: vec![0, 1, 0, 2, 3, 0, 0], the output should be: vec![0, 1, 0, 2, 3]
To do this I tried:
fn main() {
let mut vec = vec![0, 1, 0, 2, 3, 0, 0];
vec = vec.into_iter().rev().skip_while(|&x| x == 0).rev();
}
But I get these compiler errors:
error[E0277]: the trait bound `std::iter::SkipWhile<std::iter::Rev<std::vec::IntoIter<{integer}>>, [closure#src/main.rs:3:44: 3:55]>: std::iter::DoubleEndedIterator` is not satisfied
--> src/main.rs:3:57
|
3 | vec = vec.into_iter().rev().skip_while(|&x| x == 0).rev();
| ^^^ the trait `std::iter::DoubleEndedIterator` is not implemented for `std::iter::SkipWhile<std::iter::Rev<std::vec::IntoIter<{integer}>>, [closure#src/main.rs:3:44: 3:55]>`
error[E0308]: mismatched types
--> src/main.rs:3:11
|
3 | vec = vec.into_iter().rev().skip_while(|&x| x == 0).rev();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::vec::Vec`, found struct `std::iter::Rev`
|
= note: expected type `std::vec::Vec<{integer}>`
found type `std::iter::Rev<std::iter::SkipWhile<std::iter::Rev<std::vec::IntoIter<{integer}>>, [closure#src/main.rs:3:44: 3:55]>>`
The strange thing is that DoubleEndedIterator is implemented for SkipWhile. In fact, SkipWhile even implements rev(). See here.
What am I doing wrong? Is there a better approach?
The iterator adaptor for reversal only works for iterators which can be traversed from any of the two ends (as in, it is a DoubleEndedIterator). While this is the case for the original one, this is no longer possible from the moment we include skip_while. In order to follow that approach, you would have to collect the rest of the reversed vector, and only then reverse again.
I, on the other hand, would just choose to fetch the index of the first trailing zero and truncate the vector with it.
let mut vec = vec![0, 1, 0, 2, 3, 0, 0];
if let Some(i) = vec.iter().rposition(|x| *x != 0) {
let new_len = i + 1;
vec.truncate(new_len);
}
... or just grab a slice instead:
let piece = &vec[..new_len];
Playground
As the error messages state:
the trait DoubleEndedIterator is not implemented for SkipWhile<...> — Take a look at the implementation of SkipWhile:
pub struct SkipWhile<I, P> {
iter: I,
flag: bool,
predicate: P,
}
You cannot reverse an iterator built from SkipWhile because it has no way of tracking if the "current" item was skipped when you add in the ability to pull from the front and the back.
expected struct Vec, found struct Rev — You still have an iterator, but you are trying to store it where a Vec must be stored. You cannot put a type A where a type B is needed.
I would collect the vector and then reverse it in place:
fn main() {
let mut vec = vec![0, 1, 0, 2, 3, 0, 0];
vec = vec.into_iter().rev().skip_while(|&x| x == 0).collect();
vec.reverse();
println!("{:?}", vec);
assert_eq!(vec, [0, 1, 0, 2, 3]);
}
DoubleEndedIterator is implemented for SkipWhile.
This is not true. If you look at the documentation for SkipWhile, it does not list that it implements DoubleEndedIterator. Here's an example of a trait it does implement: FusedIterator.
In fact, SkipWhile even implements rev()
It doesn't actually. Iterator::rev is only implemented in the condition that Self (which is SkipWhile) implements DoubleEndedIterator, which this doesn't:
fn rev(self) -> Rev<Self>
where
Self: DoubleEndedIterator,
Just to get things started, here is a really dodgy solution:
fn main() {
let mut vec = vec![0, 1, 0, 2, 3, 0, 0];
vec = vec.into_iter().rev().skip_while(|&x| x == 0).collect();
vec = vec.into_iter().rev().collect();
}

Unweave sequence, Kotlin functional/streaming idiom

I have a sequence of interleaved data (with fixed stride) and I'd like to reduce it to a single value for each "structure" (n*stride values to n values).
I could just use loop writing into the mutable list with selected step for reader index, but I'm looking for more functional and readable approach. Any thoughts?
For example:
Input sequence consists of RGB triplets (stride 3) and output is grayscale.
Imperative way is like:
fun greyscale(stream:List<Byte>):List<Byte>{
val out = ArrayList(stream.size / 3)
var i = 0; var o = 0
while(i < stream.size)
out[o++]=(stream[i++] + stream[i++] + stream[i++])/3
return out
}
How can I make something like that without explicitly implementing a function and mutable container, but purely on functional extensions like .map and so on?
Kotlin 1.2 (Milestone 1 was released yesterday) brings the chunked method on collections. It chunks up the collection into blocks of a given size. You can use this to implement your function:
fun greyscale(stream: List<Byte>): List<Byte> =
stream.chunked(3)
.map { (it.sum() / 3).toByte() }
A possible way would be grouping by the index of the elements (in this case /3) and mapping these groups to their sum.
stream.withIndex()
.groupBy { it.index / 3 }
.toSortedMap()
.values
.map { (it.sumBy { it.value } / 3).toByte() }
Also strictly functional, but using Rx, would be possible by using window(long)
Observable.from(stream)
.window(3)
.concatMap { it.reduce(Int::plus).toObservable() }
.map { (it / 3).toByte() }
Similar to #marstran's answer, in Kotlin 1.2 you can use chunked function, but providing the transform lambda to it:
fun greyscale(stream: List<Byte>): List<Byte> =
stream.chunked(3) { it.average().toByte() }
This variant has an advantage that it doesn't instantiate a new List for every triple, but rather creates a single List and reuses it during the entire operation.
Excludes remaining elements:
const val N = 3
fun greyscale(stream: List<Byte>) = (0 until stream.size / N)
.map { it * N }
.map { stream.subList(it, it + N).sum() / N }
.map(Int::toByte)
Output
[1, 2, 3, 4, 5, 6] => [2, 5]
[1, 2, 3, 4, 5] => [2]
Includes remaining elements:
const val N = 3
fun greyscale(stream: List<Byte>) = (0 until (stream.size + N - 1) / N)
.map { it * N }
.map { stream.subList(it, minOf(stream.size, it + N)).sum() / N }
.map(Int::toByte)
Output
[1, 2, 3, 4, 5, 6] => [2, 5]
[1, 2, 3, 4, 5] => [2, 3]
Best what I'm capable of is this:
fun grayscale(rgb:List<Byte>):List<Byte>
= rgb.foldIndexed(
IntArray(rgb.size / 3),
{ idx, acc, i ->
acc[idx / 3] = acc[idx / 3] + i; acc
}).map{ (it / 3).toByte() }
Output
in: [1, 2, 3, 4, 5, 6]
out: [2, 5]
And variations with ArrayList with add and last

Is there a way to fold with index in Rust?

In Ruby, if I had an array a = [1, 2, 3, 4, 5] and I wanted to get the sum of each element times its index I could do
a.each.with_index.inject(0) {|s,(i,j)| s + i*j}
Is there an idiomatic way to do the same thing in Rust? So far, I have
a.into_iter().fold(0, |x, i| x + i)
But that doesn't account for the index, and I can't really figure out a way to get it to account for the index. Is this possible and if so, how?
You can chain it with enumerate:
fn main() {
let a = [1, 2, 3, 4, 5];
let b = a.into_iter().enumerate().fold(0, |s, (i, j)| s + i * j);
println!("{:?}", b); // Prints 40
}

Proving Not (Elem x xs) when x and xs are statically known

In Chapter 9 of Type Driven Development with Idris, we are introduced to the Elem predicate with constructors Here and There for proving that an element is a member of a vector. e.g.
oneInVector : Elem 1 [1, 2, 3]
oneInVector = Here
twoInVector : Elem 2 [1, 2, 3]
twoInVector = There Here
I'm wondering how to show that an element is not in a vector. It should perhaps be by providing a solution to this type:
notThere : Elem 4 [1, 2, 3] -> Void
notThere = ?rhs
Expression/Proof search does not come up with the answer in this case, giving:
notThere : Elem 4 [1,2,3] -> Void
notThere = \__pi_arg => ?rhs1
Scanning through the library for Data.Vect, these definitions look useful (but I'm not sure how to connect the dots):
||| Nothing can be in an empty Vect
noEmptyElem : {x : a} -> Elem x [] -> Void
noEmptyElem Here impossible
Uninhabited (Elem x []) where
uninhabited = noEmptyElem
The Elem relation is Decidable (if the element type has Decidable Equality itself), using isElem:
isElem : DecEq a => (x : a) -> (xs : Vect n a) -> Dec (Elem x xs)
The idea is to use isElem 4 [1, 2, 3] to have Idris compute the proof of Not (Elem 4 [1, 2, 3]). We'll need to build up some machinery similar to Agda's Relation.Nullary.Decidable.toWitnessFalse so that we can extract proofs from (negative) Dec results:
fromFalse : (d : Dec p) -> {auto isFalse : decAsBool d = False} -> Not p
fromFalse (Yes _) {isFalse = Refl} impossible
fromFalse (No contra) = contra
and then we can use this in your notThere definition:
notThere : Not (Elem 4 [1, 2, 3])
notThere = fromFalse (isElem 4 [1, 2, 3])
Rather than specifying my own rhs for notThere, it's better to use Idris' editor support:
Starting with:
notThere : Elem 4 [1, 2, 3] -> Void
Add definition on notThere:
notThere : Elem 4 [1, 2, 3] -> Void
notThere x = ?notThere_rhs
Case split on x:
notThere : Elem 4 [1, 2, 3] -> Void
notThere (There later) = ?notThere_rhs
Case split on later:
notThere : Elem 4 [1, 2, 3] -> Void
notThere (There (There later)) = ?notThere_rhs
Case split on later:
notThere : Elem 4 [1, 2, 3] -> Void
notThere (There (There There later))) = ?notThere_rhs
Case split on later:
notThere : Elem 4 [1,2,3] -> Void
notThere (There (There (There Here))) impossible
notThere (There (There (There (There _)))) impossible
This definition is total and so we're done:
*Elem> :total notThere
Main.notThere is Total
I'd still be interested if there's a nicer solution that uses the noEmptyElem and/or uninhabited from Data.Vect.