Lawrence  Lesch

Lawrence Lesch

1648435920

Lens: Lenses, Folds, and Traversals

Lens: Lenses, Folds, and Traversals

This package provides families of lenses, isomorphisms, folds, traversals, getters and setters.

If you are looking for where to get started, a crash course video on how lens was constructed and how to use the basics is available on youtube. It is best watched in high definition to see the slides, but the slides are also available if you want to use them to follow along.

The FAQ, which provides links to a large number of different resources for learning about lenses and an overview of the derivation of these types can be found on the Lens Wiki along with a brief overview and some examples.

Documentation is available through github (for HEAD) or hackage for the current and preceding releases.

Field Guide

Lens Hierarchy

Examples

(See wiki/Examples)

First, import Control.Lens.

ghci> import Control.Lens

Now, you can read from lenses

ghci> ("hello","world")^._2
"world"

and you can write to lenses.

ghci> set _2 42 ("hello","world")
("hello",42)

Composing lenses for reading (or writing) goes in the order an imperative programmer would expect, and just uses (.) from the Prelude.

ghci> ("hello",("world","!!!"))^._2._1
"world"
ghci> set (_2._1) 42 ("hello",("world","!!!"))
("hello",(42,"!!!"))

You can make a Getter out of a pure function with to.

ghci> "hello"^.to length
5

You can easily compose a Getter with a Lens just using (.). No explicit coercion is necessary.

ghci> ("hello",("world","!!!"))^._2._2.to length
3

As we saw above, you can write to lenses and these writes can change the type of the container. (.~) is an infix alias for set.

ghci> _1 .~ "hello" $ ((),"world")
("hello","world")

Conversely view, can be used as a prefix alias for (^.).

ghci> view _2 (10,20)
20

There are a large number of other lens variants provided by the library, in particular a Traversal generalizes traverse from Data.Traversable.

We'll come back to those later, but continuing with just lenses:

You can let the library automatically derive lenses for fields of your data type

data Foo a = Foo { _bar :: Int, _baz :: Int, _quux :: a }
makeLenses ''Foo

This will automatically generate the following lenses:

bar, baz :: Lens' (Foo a) Int
quux :: Lens (Foo a) (Foo b) a b

A Lens takes 4 parameters because it can change the types of the whole when you change the type of the part.

Often you won't need this flexibility, a Lens' takes 2 parameters, and can be used directly as a Lens.

You can also write to setters that target multiple parts of a structure, or their composition with other lenses or setters. The canonical example of a setter is 'mapped':

mapped :: Functor f => Setter (f a) (f b) a b

over is then analogous to fmap, but parameterized on the Setter.

ghci> fmap succ [1,2,3]
[2,3,4]
ghci> over mapped succ [1,2,3]
[2,3,4]

The benefit is that you can use any Lens as a Setter, and the composition of setters with other setters or lenses using (.) yields a Setter.

ghci> over (mapped._2) succ [(1,2),(3,4)]
[(1,3),(3,5)]

(%~) is an infix alias for 'over', and the precedence lets you avoid swimming in parentheses:

ghci> _1.mapped._2.mapped %~ succ $ ([(42, "hello")],"world")
([(42, "ifmmp")],"world")

There are a number of combinators that resemble the +=, *=, etc. operators from C/C++ for working with the monad transformers.

There are +~, *~, etc. analogues to those combinators that work functionally, returning the modified version of the structure.

ghci> both *~ 2 $ (1,2)
(2,4)

There are combinators for manipulating the current state in a state monad as well

fresh :: MonadState Int m => m Int
fresh = id <+= 1

Anything you know how to do with a Foldable container, you can do with a Fold

ghci> :m + Data.Char Data.Text.Lens
ghci> allOf (folded.text) isLower ["hello"^.packed, "goodbye"^.packed]
True

You can also use this for generic programming. Combinators are included that are based on Neil Mitchell's uniplate, but which have been generalized to work on or as lenses, folds, and traversals.

ghci> :m + Data.Data.Lens
ghci> anyOf biplate (=="world") ("hello",(),[(2::Int,"world")])
True

As alluded to above, anything you know how to do with a Traversable you can do with a Traversal.

ghci> mapMOf (traverse._2) (\xs -> length xs <$ putStrLn xs) [(42,"hello"),(56,"world")]
"hello"
"world"
[(42,5),(56,5)]

Moreover, many of the lenses supplied are actually isomorphisms, that means you can use them directly as a lens or getter:

ghci> let hello = "hello"^.packed
"hello"
ghci> :t hello
hello :: Text

but you can also flip them around and use them as a lens the other way with from!

ghci> hello^.from packed.to length
5

You can automatically derive isomorphisms for your own newtypes with makePrisms. e.g.

newtype Neither a b = Neither { _nor :: Either a b } deriving (Show)
makePrisms ''Neither

will automatically derive

_Neither :: Iso (Neither a b) (Neither c d) (Either a b) (Either c d)

such that

_Neither.from _Neither = id
from _Neither._Neither = id

Alternatively, you can use makeLenses to automatically derive isomorphisms for your own newtypes. e.g..

makeLenses ''Neither

will automatically derive

nor :: Iso (Either a b) (Either c d) (Neither a b) (Neither c d)

which behaves identically to _Neither above.

There is also a fully operational, but simple game of Pong in the examples/ folder.

There are also a couple of hundred examples distributed throughout the haddock documentation.

Contact Information

Contributions and bug reports are welcome!

Please feel free to contact me through github or on the #haskell IRC channel on irc.freenode.net.

-Edward Kmett

Author: Ekmett
Source Code: https://github.com/ekmett/lens 
License: View license

#haskell #javascript #functionalprogramming

What is GEEK

Buddha Community

Lens: Lenses, Folds, and Traversals

Mix Order Traversal of a Binary Tree

Given a Binary Tree consisting of** N** nodes, the task is to print its Mix Order Traversal.

Mix Order Traversal_ is a tree traversal technique, which involves any two of the existing traversal techniques like Inorder, Preorder and Postorder Traversal. Any two of them can be performed or alternate levels of given tree and a mix traversal can be obtained._

Examples:

_Input: _N = 6

_Output: __7 4 5 1 3 6 _

Explanation:

_Inorder-Preorder Mix Traversal is applied to the given tree in the following order: _

_Inorder Traversal is applied at level 0 _

_Preorder Traversal is applied at level 1 _

Inorder Traversal at level 2.

_Output: __4 5 7 1 6 3 _

#data structures #recursion #tree #inorder traversal #postorder traversal #preorder traversal #tree traversals

Post Order Traversal of Binary Tree in O(N) using O(1) space

Prerequisites:- Morris Inorder TraversalTree Traversals (Inorder, Preorder and Postorder)

Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space.

Input:   1 
       /   \
     2       3
    / \     / \
   4   5   6   7
  / \
 8   9
Output: 4 8 9 5 2 6 7 3 1

Input:   5 
       /   \
     7       3
    / \     / \
   4   11  13  9
  / \
 8   4
Output: 4 8 4 11 7 13 9 3 5 

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Method 1: Using Morris Inorder Traversal

  1. Create a dummy node and make the root as it’s left child.
  2. Initialize current with dummy node.
  3. While current is not NULL
  • If current does not have a left chil traverse the right child, current = current->right
  • Otherwise,
  1. Find the right most child in the left subtree.
  2. If right most child’s right child is NULL
  • Make current as the right child of the right most node.
  • Traverse the left child, current = current->left
  1. Otherwise,
  • Set the right most child’s right pointer to NULL.
  • From current’s left child, traverse along the right children until the right most child and reverse the pointers.
  • Traverse back from right most child to current’s left child node by reversing the pointers and printing the elements.
  1. Traverse the right child, current = current->right

Below is the diagram showing the right most child in left subtree, pointing to it’s inorder successor.

Below is the diagram which highlights the path 1->2->5->9 and the way the nodes are processed and printed as per the above algorithm.

Below is the implementation of the above approach:

  • Java

filter_none

edit

play_arrow

brightness_4

// Java program to implement

// Post Order traversal

// of Binary Tree in O(N)

// time and O(1) space

// Definition of the

// binary tree

**class** TreeNode {

**public** **int** data;

**public** TreeNode left;

**public** TreeNode right;

**public** TreeNode(``**int** data)

{

**this**``.data = data;

}

**public** String toString()

{

**return** data + " "``;

}

}

**public** **class** PostOrder {

TreeNode root;

// Function to find Post Order

// Traversal Using Constant space

**void** postOrderConstantspace(TreeNode

root)

{

**if** (root == **null**``)

**return**``;

TreeNode current

= **new** TreeNode(-``1``),

pre = **null**``;

TreeNode prev = **null**``,

succ = **null**``,

temp = **null**``;

current.left = root;

**while** (current != **null**``) {

// Go to the right child

// if current does not

// have a left child

**if** (current.left == **null**``) {

current = current.right;

}

**else** {

// Traverse left child

pre = current.left;

// Find the right most child

// in the left subtree

**while** (pre.right != **null**

&& pre.right != current)

pre = pre.right;

**if** (pre.right == **null**``) {

// Make current as the right

// child of the right most node

pre.right = current;

// Traverse the left child

current = current.left;

}

**else** {

pre.right = **null**``;

succ = current;

current = current.left;

prev = **null**``;

// Traverse along the right

// subtree to the

// right-most child

**while** (current != **null**``) {

temp = current.right;

current.right = prev;

prev = current;

current = temp;

}

// Traverse back from

// right most child to

// current's left child node

**while** (prev != **null**``) {

System.out.print(prev);

temp = prev.right;

prev.right = current;

current = prev;

prev = temp;

}

current = succ;

current = current.right;

}

}

}

}

// Driver Code

**public** **static** **void** main(String[] args)

{

/* Constructed tree is as follows:-

/     \

2       3

/ \     / \

4   5   6   7

/ \

8   9

*/

PostOrder tree = **new** PostOrder();

tree.root = **new** TreeNode(``1``);

tree.root.left = **new** TreeNode(``2``);

tree.root.right = **new** TreeNode(``3``);

tree.root.left.left = **new** TreeNode(``4``);

tree.root.left.right

= **new** TreeNode(``5``);

tree.root.right.left

= **new** TreeNode(``6``);

tree.root.right.right

= **new** TreeNode(``7``);

tree.root.left.right.left

= **new** TreeNode(``8``);

tree.root.left.right.right

= **new** TreeNode(``9``);

tree.postOrderConstantspace(

tree.root);

}

}

Output:

4 8 9 5 2 6 7 3 1

_Time Complexity: _O(N)

Auxiliary Space:_ O(1)_

Method 2: In method 1, we traverse a path, reverse references, print nodes as we restore the references by reversing them again. In method 2, instead of reversing paths and restoring the structure, we traverse to parent node from the current node using the current node’s left subtree. This could be faster depending on the tree structure, for example in a right-skewed tree.

The following algorithm and diagrams provide the details of the approach.

#data structures #recursion #tree #inorder traversal #interview-preparation #morris-traversal #postorder traversal

Lawrence  Lesch

Lawrence Lesch

1648435920

Lens: Lenses, Folds, and Traversals

Lens: Lenses, Folds, and Traversals

This package provides families of lenses, isomorphisms, folds, traversals, getters and setters.

If you are looking for where to get started, a crash course video on how lens was constructed and how to use the basics is available on youtube. It is best watched in high definition to see the slides, but the slides are also available if you want to use them to follow along.

The FAQ, which provides links to a large number of different resources for learning about lenses and an overview of the derivation of these types can be found on the Lens Wiki along with a brief overview and some examples.

Documentation is available through github (for HEAD) or hackage for the current and preceding releases.

Field Guide

Lens Hierarchy

Examples

(See wiki/Examples)

First, import Control.Lens.

ghci> import Control.Lens

Now, you can read from lenses

ghci> ("hello","world")^._2
"world"

and you can write to lenses.

ghci> set _2 42 ("hello","world")
("hello",42)

Composing lenses for reading (or writing) goes in the order an imperative programmer would expect, and just uses (.) from the Prelude.

ghci> ("hello",("world","!!!"))^._2._1
"world"
ghci> set (_2._1) 42 ("hello",("world","!!!"))
("hello",(42,"!!!"))

You can make a Getter out of a pure function with to.

ghci> "hello"^.to length
5

You can easily compose a Getter with a Lens just using (.). No explicit coercion is necessary.

ghci> ("hello",("world","!!!"))^._2._2.to length
3

As we saw above, you can write to lenses and these writes can change the type of the container. (.~) is an infix alias for set.

ghci> _1 .~ "hello" $ ((),"world")
("hello","world")

Conversely view, can be used as a prefix alias for (^.).

ghci> view _2 (10,20)
20

There are a large number of other lens variants provided by the library, in particular a Traversal generalizes traverse from Data.Traversable.

We'll come back to those later, but continuing with just lenses:

You can let the library automatically derive lenses for fields of your data type

data Foo a = Foo { _bar :: Int, _baz :: Int, _quux :: a }
makeLenses ''Foo

This will automatically generate the following lenses:

bar, baz :: Lens' (Foo a) Int
quux :: Lens (Foo a) (Foo b) a b

A Lens takes 4 parameters because it can change the types of the whole when you change the type of the part.

Often you won't need this flexibility, a Lens' takes 2 parameters, and can be used directly as a Lens.

You can also write to setters that target multiple parts of a structure, or their composition with other lenses or setters. The canonical example of a setter is 'mapped':

mapped :: Functor f => Setter (f a) (f b) a b

over is then analogous to fmap, but parameterized on the Setter.

ghci> fmap succ [1,2,3]
[2,3,4]
ghci> over mapped succ [1,2,3]
[2,3,4]

The benefit is that you can use any Lens as a Setter, and the composition of setters with other setters or lenses using (.) yields a Setter.

ghci> over (mapped._2) succ [(1,2),(3,4)]
[(1,3),(3,5)]

(%~) is an infix alias for 'over', and the precedence lets you avoid swimming in parentheses:

ghci> _1.mapped._2.mapped %~ succ $ ([(42, "hello")],"world")
([(42, "ifmmp")],"world")

There are a number of combinators that resemble the +=, *=, etc. operators from C/C++ for working with the monad transformers.

There are +~, *~, etc. analogues to those combinators that work functionally, returning the modified version of the structure.

ghci> both *~ 2 $ (1,2)
(2,4)

There are combinators for manipulating the current state in a state monad as well

fresh :: MonadState Int m => m Int
fresh = id <+= 1

Anything you know how to do with a Foldable container, you can do with a Fold

ghci> :m + Data.Char Data.Text.Lens
ghci> allOf (folded.text) isLower ["hello"^.packed, "goodbye"^.packed]
True

You can also use this for generic programming. Combinators are included that are based on Neil Mitchell's uniplate, but which have been generalized to work on or as lenses, folds, and traversals.

ghci> :m + Data.Data.Lens
ghci> anyOf biplate (=="world") ("hello",(),[(2::Int,"world")])
True

As alluded to above, anything you know how to do with a Traversable you can do with a Traversal.

ghci> mapMOf (traverse._2) (\xs -> length xs <$ putStrLn xs) [(42,"hello"),(56,"world")]
"hello"
"world"
[(42,5),(56,5)]

Moreover, many of the lenses supplied are actually isomorphisms, that means you can use them directly as a lens or getter:

ghci> let hello = "hello"^.packed
"hello"
ghci> :t hello
hello :: Text

but you can also flip them around and use them as a lens the other way with from!

ghci> hello^.from packed.to length
5

You can automatically derive isomorphisms for your own newtypes with makePrisms. e.g.

newtype Neither a b = Neither { _nor :: Either a b } deriving (Show)
makePrisms ''Neither

will automatically derive

_Neither :: Iso (Neither a b) (Neither c d) (Either a b) (Either c d)

such that

_Neither.from _Neither = id
from _Neither._Neither = id

Alternatively, you can use makeLenses to automatically derive isomorphisms for your own newtypes. e.g..

makeLenses ''Neither

will automatically derive

nor :: Iso (Either a b) (Either c d) (Neither a b) (Neither c d)

which behaves identically to _Neither above.

There is also a fully operational, but simple game of Pong in the examples/ folder.

There are also a couple of hundred examples distributed throughout the haddock documentation.

Contact Information

Contributions and bug reports are welcome!

Please feel free to contact me through github or on the #haskell IRC channel on irc.freenode.net.

-Edward Kmett

Author: Ekmett
Source Code: https://github.com/ekmett/lens 
License: View license

#haskell #javascript #functionalprogramming

Elisa  Marks

Elisa Marks

1600698540

Python built-in len() Function Example

You can use the len() function to any iterable objects. It returns an integer which is the length of that iterable object.

Python len Example

Python len() is an inbuilt function that returns the length of any iterable objects. It returns the no. of characters of String; it returns the total number of items of list or dictionary.

The syntax of the Python len function is the following.

len(any iterable object)

An only required argument is an iterable object which can be a list, string or dictionary.

#python #len() function #python len

What is Manifold Finance (FOLD) | What is Manifold Finance token | What is FOLD token

In this article, we’ll discuss information about the Manifold Finance project and FOLD token.

Manifold is a multi-protocol middleware solution to improve connectivity between DeFi products.

With YCabal, we are redefining transactions. We guard traders against on-chain predatory arbitragers via our MEV-based solution, while drastically decreasing gas fees.

Our governance system allows participants to buy in to our technology and benefit from the strategies in a way they can generate passive yield, while also engaging with the governance process that drives these integrations.

Safe passage through the dark forest

Currently, you as a trader are forced to directly put your transactions on-chain. From that point on, you’re helpless. Nefarious actors can target your transactions whenever they want, eventually causing you to pay extra gas fees, which are already egregiously high.

With YCabal, we’re giving traders a shield to protect themselves against those ‘creatures’. This process guarantees that your transaction gets posted and creates a situation where you can have the majority of your gas fees refunded.

YCabal’s Core Benefits

1. Shield your transactions

2. Save on gas costs

3. **Reduce **failed transactions

How it works

You, the user, opt-in for YCabal to leverage Manifold’s MEV-RPC layer to shield yourself from predatory on-chain arbitrage. Transaction order flow into the algorithm gets analyzed to identify arbitrage opportunities. This happens within nano-seconds, assuring minimal lag-time. From here the transaction is being sent directly into the mining pool. The profits are then shared between network participants.

Effectively, you’ll be paying _near zero gas fees, _and that _‘fail’ _message may become a thing of the past.

SHAPING THE FUTURE OF MANIFOLD

Governance

Governance participants can opt-in to a portion of the yield from our middleware strategy. At the end of the staking sessions, you’ll be able to receive yield.

Network participants can buy in to our technology and benefit from the strategies in a way that generates passive yield, while also engaging with the governance mechanism that drives these integrations.

A TRULY DEMOCRATIC SYSTEM

Voting

Network participants are democratically involved in governance votes. You’ll be a able to vote on integration partnerships and strategies.

You’re not just impacting the direction that strategies will take, but also the distribution of the revenue that each one generates. With Manifold, you will influence how the future gets built.

DeFi Protocols

manifold-fold-graphicAs a result of the benefits that our solutions bring, your platform’s user experience naturally improves. In addition to that, DeFi protocols that integrate with our technologies also share in the revenue of our strategies.

manifold-fold-graphic

STRATEGIES

From trade execution infrastructure to on-chain protocol extensions, Manifold

Finance has built a scalable stack of DeFi products with a focus of enhancing and providing additional functionality to DeFi protocols.

manifold-fold-graphic

MAKING YOUR LIFE EASIER

Manifold middleware, such as YCabal, is plug and play. Whereas integration with other middleware often requires changes to the foundation layer of the protocol, ours require minimal changes to implement.

Additionally, YCabal builds its own RPC end points, allowing developers to identify bugs and resolve them swiftly. On top of that, we’re giving developers more choice in terms of capabilities.

How and Where to Buy FOLD token ?

FOLD has been listed on a number of crypto exchanges, unlike other main cryptocurrencies, it cannot be directly purchased with fiats money. However, You can still easily buy this coin by first buying Bitcoin, ETH, USDT, BNB from any large exchanges and then transfer to the exchange that offers to trade this coin, in this guide article we will walk you through in detail the steps to buy FOLD.

You will have to first buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

We will use Binance Exchange here as it is one of the largest crypto exchanges that accept fiat deposits.

Binance is a popular cryptocurrency exchange which was started in China but then moved their headquarters to the crypto-friendly Island of Malta in the EU. Binance is popular for its crypto to crypto exchange services. Binance exploded onto the scene in the mania of 2017 and has since gone on to become the top crypto exchange in the world.

Once you finished the KYC process. You will be asked to add a payment method. Here you can either choose to provide a credit/debit card or use a bank transfer, and buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

SIGN UP ON BINANCE

Step by Step Guide : What is Binance | How to Create an account on Binance (Updated 2021)

Next step - Transfer your cryptos to an Altcoin Exchange

Once finished you will then need to make a BTC/ETH/USDT/BNB deposit to the exchange from Binance depending on the available market pairs. After the deposit is confirmed you may then purchase FOLD from the website: https://www.manifoldfinance.com.

The top exchange for trading in FOLD token is currently 

Find more information FOLD

WebsiteExplorerSource CodeSocial ChannelSocial Channel 2DocumentationCoinmarketcap

🔺DISCLAIMER: The Information in the post isn’t financial advice, is intended FOR GENERAL INFORMATION PURPOSES ONLY. Trading Cryptocurrency is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money.

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner

⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!

☞ **-----CLICK HERE-----**⭐ ⭐ ⭐

I hope this post will help you. Don’t forget to leave a like, comment and sharing it with others. Thank you!

#blockchain #bitcoin #fold #manifold finance