I'm experimenting with the Pure language based on term rewriting.
I want to define "map fusion" using an equation, like this:
> map f (map g list) = map (f . succ . g) list;
(The succ is there to verify that the rule kicks in.)
However, it doesn't seem to work:
> map id (map id [2,3,4]);
[2,3,4]
The Pure manual says that
expressions are evaluated using the “leftmost-innermost” reduction strategy
So I suppose what's happening is that the innermost map id [2,3,4] expression is reduced first, so my rule never kicks in.
How to make map fusion work, then?
Here's a related experiment. The first rule doesn't kick in:
> a (b x) = "foo";
> b x = "bar";
> a (b 5);
a "bar"
I should have read the manual more closely. What I needed to do is to turn the pattern into a macro using the def keyword. This way it works:
> def map f (map g list) = map (f . succ . g) list;
> map id (map id [2,3,4]);
[3,4,5]
Related
The function should take a list of tuples, and return the ones that have sum > 5
Let's say I have the following code:
fn :: [(Int, Int)] -> [(Int, Int)]
fn tuples = map (\(x,y) -> if (x + y) > 5 then (x,y) else (0,0)) tuples
fn [(3,4), (4,4), (0,1)] returns [(3,4),(4,4),(0,0)] but really I just want it to return [(3,4),(4,4)]
Is this possible in haskell while still following the type signature?
What you're asking for is mapMaybe:
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
base Data.Maybe
The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it is Just b, then b is included in the result list.
The smallest change to use it in your code would be:
import Data.Maybe
fn :: [(Int, Int)] -> [(Int, Int)]
fn tuples = mapMaybe (\(x,y) -> if (x + y) > 5 then Just (x,y) else Nothing) tuples
However, in this specific case, you don't actually transform, you just remove. If you don't plan on adding transformation later, filter is more suitable:
fn = filter (\(x,y) -> x+y > 5)
Bit of a weird question, but after the comment
I dont see a concept of “empty tuple” in haskell
I guess I see where you're coming from. Actually Haskell does have “empty tuples”: the unit type () is the type of “tuples with zero elements”. So what you're thinking of seems to be
fn tuples = map (\(x,y) -> if x + y > 5 then (x,y) else ()) tuples
But that doesn't work because () is a different type from (Int,Int). The elements of a list must all have the same type. Even if it did work, à la dynamic-types, the result of fn [(3,4), (4,4), (0,1)] would then actually be [(3,4), (4,4), ()]. I.e. you'd still get three elements, just one of them would be “boring”.
map does in fact by design guarantee to never change the number of elements in the list, only the values of their elements. So if that's what you want, you need to use a different function. The closest to your approach would be concatMap:
fn tuples = concatMap (\(x,y) -> if x + y > 5 then [(x,y)] else []) tuples
What happens here can also be described in two steps:
You map a function that generates a list for each element. The result is thus a list of lists.
You flatten that list.
So [(3,4), (4,4), (0,1)] -> [[(3,4)], [(4,4)], []] -> [(3,4), (4,4)].
Really though, there's no need to use a mapping step at all here – the elements are kept as they are eventually, so filter is the tool to use.
I am working through the Purescript By Example tutorial and I am having trouble getting types to line up using a fold left as such:
smallestFile' :: [Path] -> Maybe Path
smallestFile' (x : xs) = foldl(\acc i -> smallerFile(acc i) ) Just(x) xs // Error is on this line
smallerFile :: Maybe Path -> Path -> Maybe Path
smallerFile maybeA b = do
a <- maybeA
sa <- size a
sb <- size b
if sa > sb then return(b) else return(a)
The error I am receiving is on the fold left and is
Cannot unify Prim.Function u13116 with Data.Maybe.Maybe
I believe that the types line up, but I cannot make heads or tails of this error.
Also, is it possible to clean up the anonymous function syntax so that
foldl(\acc i -> smallerFile(acc i) ) Just(x) xs
becomes something like:
foldl smallerFile Just(x) xs
In PureScript, like Haskell, function application uses whitespace, and associates to the left, which means that f x y z parses as ((f x) y) z. You only need parentheses when terms need to be regrouped. It looks like you're trying to use parentheses for function application.
I suspect what you want to write is
foldl (\acc i -> smallerFile acc i) (Just x) xs
The argument to foldl is a function which takes two arguments acc and i and returns the application smallerFile acc i. This is equivalent to the double application (smallerFile acc) i. First we apply the argument acc, then the second argument i. The precedence rule for function application in the parser makes these equivalent.
Also, Just x needs to be parenthesized because what you wrote parses as
foldl (\acc i -> smallerFile (acc i)) Just x xs
which provides too many arguments to foldl.
Once you have the correct version, you can notice that \acc i -> smallerFile acc i is equivalent to \acc -> (\i -> (smallerFile acc) i). The inner function applies its argument i immediately, so we can simplify this to \acc -> smallerFile acc. Applying this simplification a second time, we get just smallerFile, so the code becomes:
foldl smallerFile (Just x) xs
so the only mistake in the end was the incorrect bracketing of Just x.
I am trying to produce the solution for an intersection of two sets using tail recursion and an empty list [] as an accu:
let rec setintersect list list =
let rec setintersect2 a b c =
match a with
| [] -> (match b with [] -> (setsimplify c) | h::t -> (setsimplify c))
| h1::t1 -> (match b with [] -> (setsimplify c) |h2::t2 -> (if (elementof h1 b) then (setintersect2 t1 b (c#[h1])) else (setintersect2 t1 b c))) in
setintersect2 list list [];;
Elementof takes takes "an int and a list" and is correctly working to give true if x is an element of the list, false otherwise..
Here is the problem:
# setintersect [5;2;1] [2;6;9];;
- : int list = [2; 6; 9]
and it should give [2].
What am I doing wrong?
I feel like there's something really simple that I am misunderstanding!
Edit:
Thanks for the responses so far.
setsimplify just removes the duplicates.
so [2,2,3,5,6,6] becomes [2,3,5,6]. Tested and made sure it is working properly.
I am not supposed to use anything from the List library either. Also, I must use "tail recursion" with the accumulator being a list that I build as I go.
Here is the thought:
Check the head element in list1, IF it exists in list2, THEN recurse with the "tail of list1, list2, and list c with that element added to it". ELSE, then recurse with "tail of list1, list2 and list c(as it is)".
end conditions are either list1 or list2 are empty or both together are empty, return list c (as it is).
let rec setintersect list list = is wrong: the two arguments should be named differently (you should of course update the call to setintersect2 accordingly), otherwise the second will shadow the first. I would have thought that OCaml would have at least warned you about this fact, but it appears that it is not the case.
Apart from that, the code seems to do the trick. There are a couple of things that could be improved though:
setintersect itself is not recursive (only setintersect2 is), you thus don't need the rec
you should find a different name for the argument of setintersect2. In particular, it is not obvious which is the accumulator (acc or accu will be understood by most OCaml programmers in these circumstances).
c#[h1] is inefficient: you will traverse c completely each time you append an element. It's better to do h1::c and reverse the result at the end
As a bonus point, if you append element at the beginning of c, and assume that a is ordered, you don't have to call setsimplify at the end of the call: just check whether c is empty, and if this is not the case, append h1 only if it is not equal to the head of c.
First, You didn't list out your setsimplify function.
To write an ocaml function, try to split it first, and then combine if possible.
To solve this task, you just go through all elements in l1, and for every element, you check whether it is in l2 or not, right?
So definitely you need a function to check whether an element is in a list or not, right?
let make one:
let rec mem x = function
| [] -> false
| hd::tl -> hd = x || mem x tl
Then you can do your intersection:
let rec inter l1 l2 =
match l1 with
| [] -> []
| hd::tl -> if mem hd l2 then hd::(inter tl l2) else inter tl l2
Note that the above function is not tail-recursive, I guess you can change it to tail-recursive as an excise.
If you use std library, then it is simple:
let intersection l1 l2 = List.filter (fun x -> List.mem x l2) l1
I feel like this should be fairly obvious, or easy, but I just can't get it. What I want to do is apply a function to a list (using map) but only if a condition is held. Imagine you only wanted to divide the numbers which were even:
map (`div` 2) (even) [1,2,3,4]
And that would give out [1,1,3,2] since only the even numbers would have the function applied to them. Obviously this doesn't work, but is there a way to make this work without having to write a separate function that you can give to map? filter is almost there, except I also want to keep the elements which the condition doesn't hold for, and just not apply the function to them.
If you don't want to define separate function, then use lambda.
map (\x -> if (even x) then (x `div` 2) else x) [1,2,3,4]
Or instead of a map, list comprehension, bit more readable I think.
[if (even x) then (x `div` 2) else x | x <- [1,2,3,4]]
mapIf p f = map (\x -> if p x then f x else x)
In addition to the answer of PiotrLegnica: Often, it's easier to read if you declare a helper function instead of using a lambda. Consider this:
map helper [1..4] where
helper x | even x = x `div` 2
| otherwise = x
([1..4] is sugar for [1,2,3,4])
If you want to remove all the other elements instead, consider using filter. filter removes all elements that don't satisfy the predicate:
filter even [1..4] -> [2,4]
So you can build a pipe of mapand filter than or use list-comprehension instead:
map (`div` 2) $ filter even [1..4]
[x `div` 2 | x <- [1..4], even x]
Choose whatever you like best.
Make your own helper function maker:
ifP pred f x =
if pred x then f x
else x
custom_f = ifP even f
map custom_f [..]
(caveat: I don't have access to a compiler right now. I guess this works OK...)
I like the other, more general solutions, but in your very special case you can get away with
map (\x -> x `div` (2 - x `mod` 2)) [1..4]
Mostly a rip off of existing answers, but according to my biased definition of "readable" (I like guards more than ifs, and where more than let):
mapIf p f = map f'
where f' x | p x = f x | otherwise = x
ghci says it probably works
ghci> let mapIf p f = map f' where f' x | p x = f x | otherwise = x
ghci> mapIf even (+1) [1..10]
[1,3,3,5,5,7,7,9,9,11]
I'm new to ocaml and tryin to write a continuation passing style function but quite confused what value i need to pass into additional argument on k
for example, I can write a recursive function that returns true if all elements of the list is even, otherwise false.
so its like
let rec even list = ....
on CPS, i know i need to add one argument to pass function
so like
let rec evenk list k = ....
but I have no clue how to deal with this k and how does this exactly work
for example for this even function, environment looks like
val evenk : int list -> (bool -> ’a) -> ’a = <fun>
evenk [4; 2; 12; 5; 6] (fun x -> x) (* output should give false *)
The continuation k is a function that takes the result from evenk and performs "the rest of the computation" and produces the "answer". What type the answer has and what you mean by "the rest of the computation" depends on what you are using CPS for. CPS is generally not an end in itself but is done with some purpose in mind. For example, in CPS form it is very easy to implement control operators or to optimize tail calls. Without knowing what you are trying to accomplish, it's hard to answer your question.
For what it is worth, if you are simply trying to convert from direct style to continuation-passing style, and all you care about is the value of the answer, passing the identity function as the continuation is about right.
A good next step would be to implement evenk using CPS. I'll do a simpler example.
If I have the direct-style function
let muladd x i n = x + i * n
and if I assume CPS primitives mulk and addk, I can write
let muladdk x i n k =
let k' product = addk x product k in
mulk i n k'
And you'll see that the mulptiplication is done first, then it "continues" with k', which does the add, and finally that continues with k, which returns to the caller. The key idea is that within the body of muladdk I allocated a fresh continuation k' which stands for an intermediate point in the multiply-add function. To make your evenk work you will have to allocate at least one such continuation.
I hope this helps.
Whenever I've played with CPS, the thing passed to the continuation is just the thing you would normally return to the caller. In this simple case, a nice "intuition lubricant" is to name the continuation "return".
let rec even list return =
if List.length list = 0
then return true
else if List.hd list mod 2 = 1
then return false
else even (List.tl list) return;;
let id = fun x -> x;;
Example usage: "even [2; 4; 6; 8] id;;".
Since you have the invocation of evenk correct (with the identity function - effectively converting the continuation-passing-style back to normal style), I assume that the difficulty is in defining evenk.
k is the continuation function representing the rest of the computation and producing a final value, as Norman said. So, what you need to do is compute the result of v of even and pass that result to k, returning k v rather than just v.
You want to give as input the result of your function as if it were not written with continuation passing style.
Here is your function which tests whether a list has only even integers:
(* val even_list : int list -> bool *)
let even_list input = List.for_all (fun x -> x mod 2=0) input
Now let's write it with a continuation cont:
(* val evenk : int list -> (bool -> 'a) -> 'a *)
let evenk input cont =
let result = even_list input in
(cont result)
You compute the result your function, and pass resultto the continuation ...