I would like to transform the following tuple list
a = [(1,()),(2,())]
into a nested tuple list by the same value
b = [(False,(1,())),(False,(2,()))]
Using the zip function in this format
zip [False] a
only gives me
[(False,(1,()))]
Any suggestions or advice would be much appreciated.
If you zip two lists of different lengths, you get the length of the shortest list.
You can fix this by zipping against an infinitely long list:
zip (repeat False) a
should do the trick.
Alternatively, instead of using zip you can use map:
map (\x -> (False, x)) a
This would more appropriately express your intent (in my opinion) since you want to do the same thing to every element of the list. If you want to do different things to each element, then zip or zipWith may be more appropriate.
If you wanted to avoid the lambda, you can write it pointfree using &&& from Control.Arrow:
map (const False &&& id) a
which basically says "apply the functions const False and id to the input, then construct a tuple of both of their outputs". There is the TupleSections extension which would allow you to write this as
map (False,) a
(tip provided by #thoferon), but I personally find this less clear, since you have to know that the extension is enabled and notice the , after False. You could write it as
map ((,) False) a
without the extension since (,) acts as a function of type a -> b -> (a, b), and while a bit more verbose it doesn't require enabling a language extension.
In addition to others answers it is also possible to write a generic function for any Functor, not just for lists:
strengthL :: Functor f => a -> f b -> f (a, b)
strengthL = fmap . (,)
strengthR :: Functor f => a -> f b -> f (b, a)
strengthR = fmap . flip (,)
Then strengthL can be applied to False and the original list:
Prelude> strengthL False [(1,()),(2,())]
[(False,(1,())),(False,(2,()))]
Related
so I am new to OCaml and im having some trouble with lists.
What I have is a List of chars as follows:
let letters = [a;b;c;d]
I would like to know how can I iterate the list and apply a fuction that takes as arguments every possible combination of two chars on the list (do_someting char1 char2), for example: a and b (do_something a b), a and c .... d and b, d and c; never repeating the same element (a and a or c and c should not happen).
OCaml is a functional language, so we want to try to break down the procedure into as many functional pieces as we can.
Step 1 is "take a list of things and produce all combinations". We don't care what happens afterward; we just want to know all such combinations. If you want each combination to appear only once (i.e. (a, b) will appear but (b, a) will not, in your example), then a simple recursive definition will suffice.
let rec ordered_pairs xs =
match xs with
| [] -> []
| (x :: xs) -> List.append (List.map (fun y -> (x, y)) xs) (ordered_pairs xs)
If you want the reversed duplicates ((a, b) and (b, a)), then we can add them in at the end.
let swap (x, y) = (y, x)
let all_ordered_pairs xs =
let p = ordered_pairs xs in
List.append p (List.map swap p)
Now we have a list of all of the tuples. What happens next depends on what kind of result you want. In all likelihood, you're looking at something from the built-in List module. If you want to apply the function to each pair for the side effects, List.iter does the trick. If you want to accumulate the results into a new list, List.map will do it. If you want to apply some operation to combine the results (say, each function returns a number and you want the sum of the numbers), then List.map followed by List.fold_left (or the composite List.fold_left_map) will do.
Of course, if you're just starting out, it can be instructive to write these List functions yourself. Every one of them is a simple one- or two- line recursive definition and is very instructive to write on your own.
I am to use combinators and no for/while loops, recursion or defined library functions from F#'s List module, except constructors :: and []
Ideally I want to implement map
I am trying to write a function called llength that returns the list of the lengths of the sublists. For example llength [[1;2;3];[1;2];[1;2;3]] should return [3;2,3]. I also have function length that returns the length of a list.
let Tuple f = fun a b -> f (a, b)
let length l : int =
List.fold (Tuple (fst >> (+) 1)) 0 l
currently have
let llength l : int list =
List.map (length inner list) list
Not sure how I should try accessing my sublists with my restraints and should I use my other method on each sublist? any help is greatly appreciated, thanks!
Since this is homework, I don't want to just give you a fully coded solution, but here are some hints:
First, since fold is allowed you could implement map via fold. The folding function would take the list accumulated "so far" and prepend the next element transformed with mapping function. The result will come out reversed though (fold traverses forward, but you prepend at every step), so perhaps that wouldn't work for you if you're not allowed List.rev.
Second - the most obvious, fundamental way: naked recursion. Here's the way to think about it: (1) when the argument is an empty list, result should be an empty list; (2) when the argument is a non-empty list, the result should be length of the argument's head prepended to the list of lengths of the argument's tail, which can be calculated recursively. Try to write that down in F#, and there will be your solution.
Since you can use some functions that basically have a loop (fold, filter ...), there might be some "cheated & dirty" ways to implement map. For example, via filter:
let mymap f xs =
let mutable result = []
xs
|> List.filter (fun x ->
result <- f x :: result
true)
|> ignore
result |> List.rev
Note that List.rev is required as explained in the other answer.
I built a list of this structure:
[(Interger, Double)]
The List was created by using a zip over a list of Integers and a list of Doubles of exactly the same size.
Now I want to filter the list for Doubles that are either <18.5 or >25. The problem I have is I can't access the Doubles to use them in the filter function.
It's probably easy but I'm a bloody noob in this language. I googled around a lot and read some other threads but I didn't find an answer.
I got:
filter (<18.5) listexpression
So what I'm struggling with is that listexpression. It's easy if it's a list of single values. I could filter before zipping but then I can't connect the data from the filtered list to the other unfiltered List anymore.
Edit: I forgot to mention. It's a worksheet. We were asked to build filter and map functions ourselves and are not allowed to use any additions to the basic Haskell. Meaning no imports are allowed.
You can do something like this:
Prelude> filter (\p -> (snd p) < 18.5 || (snd p) > 25) [(1, 2.3), (1, 20.0)]
[(1,2.3)]
The lambda function passed to filter, namely
(\p -> (snd p) < 18.5 || (snd p) > 25)
says that for every p, the second element of p must be less than 18.5 or over 25.
Alternatively, you could write it like this
Prelude> filter (\(_, f) -> f < 18.5 || f > 25) [(1, 2.3), (1, 20.0)]
[(1,2.3)]
Here the function says that for any pair whose first value doesn't matter and the second one is f, f must be less than 18.5 or over 25.
Glad to see Ami Tavory's answer solved your problem.
But under that answer, you commented:
I tried accessing it with a combination of (!!) but that didn't work.
With the insight of a teaching assistant [:D], I guess you confused list with tuple in Haskell.
zip returns a list of tuple, whereas (!!) take a list as (the first) argument (hence (!!1) take a single list argument), so (!!1) can't be applied to elements of the list returned by zip, which are of type tuple.
Prelude> :t zip
zip :: [a] -> [b] -> [(a, b)]
Prelude> :t (!!)
(!!) :: [a] -> Int -> a
Prelude> :t (!!1)
(!!1) :: [a] -> a
And you've known that fst and snd are applied to tuple.
Prelude> :t fst
fst :: (a, b) -> a
Prelude> :t snd
snd :: (a, b) -> b
A compact version using point free style would be
filter ((>18.5).snd) listexpression
This uses the function composition operator ., which reads as: First apply the snd function to a tuple from the list to extract the 2nd value, then apply the comparison to 18.5 to this value.
Just for a variety and some additional information which won't bite...
In Haskell the list type is an instance of Monad class. So a list operation like filter can simply be implemented by a monadic bind operator.
*Main> [(1,2.3),(3,21.2),(5,17.1),(4,24.4)] >>= \t -> if snd t < 25 && snd t > 18.5 then [t] else []
[(3,21.2),(4,24.4)]
Monad is all about handling the contained data in a sequential manner. In the list monad the contained data is the value within the list itself. So the bind operator can be very handy to access to contained values (tuples) of the monadic value (the list of tuples) in a sequential manner.
(>>=) :: Monad m => m a -> (a -> m b) -> m b
The type signature of the monadic bind operator states that it takes a monad type value m a as the first argument (the list of tuples here) and a function as the second argument which takes a pure value and returns a monadic value (takes a tuple and returns a tuple in a list or an empty list in this case).
\t -> if snd t < 25 && snd t > 18.5 then [t] else []
It's critical to understand how and why the list items are applied one by one to the provided function. An entire list is one monadic value and the contained values those accessed by the bind operator are passed to the provided a -> m b (take a pure value and return monadic value) type function. So all of the list items those applied to this function become a monadic value ([t] if condition satisfies or [] if it fails), are then concatenated by the bind operator to form one monadic return value (in this case a list of tuples those satisfy the condition which is implemented in the lambda function).
This monadic operation can also be implemented with the do notation
do
t <- [(1,2.3),(3,21.2),(5,17.1),(4,24.4)]
if snd t < 25 && snd t > 18.5 then return t else []
[(3,21.2),(4,24.4)]
Of course this terribly resembles the list comprehensions which is in fact a syntactical sugar to the monadic list operations. So lets implement it for a final time by using the list comprehensions.
*Main> [t | t <- [(1,2.3),(3,21.2),(5,17.1),(4,24.4)], snd t < 25 && snd t > 18.5]
[(3,21.2),(4,24.4)]
I'm just starting to learn Haskell, and I have to create a function composite that receives two lists a, b :: [(String, String)] as inputs, and outputs a new list c :: [(String, String)], which is a 'composition' of both a and b. Specifically, list c has to include only those pairs (p,q), where there is a r such that:
(p,r) is in a
(r,q) in in b
For example:
composite [("1","2")] [("2","3"), ("2","4")] == [("1","3"), ("1","4")]
composite [("1","2"), ("5","2")] [("2","3"), ("2","4")] == [("1","3"), ("1","4"), ("5","3"), ("5","4")]
composite [("1","2"), ("1","4"), ("1","5")] [("2","3"), ("4","3")] == [("1","3")]
How can I do this?
You can combine the lists using a list comprehension over multiple lists:
[(x,z)|(x,y) <- a, (y',z) <- b, y == y' ]
Note that the result is the list if (x,z) tuples, and the inputs are the lists of (x,y) and (y,z) tuples.
I have tried this in http://tryhaskell.org with your list test case; feel free to copy-paste it there and play around with it:
[(x,z) | (x,y) <-[('a', 'b'), ('a', 'd'), ('a', 'e')],(y',z) <- [('b','c'), ('d','c')], y == y']
This yields:
[('a','c'),('a','c')]
There are a few other things to note.
First, the y == y'. As #chi points out, if you use 'y' again in the list comprehension, the system does not consider it the same variable. You need to use a new variable, y' (or any other name) and explicitly tell Haskell that y and y' should have the same value.
Second, we're not using capitals; Haskell is case-sensitive and uses capitals for other purposes.
Third, you don't have to make it only for Strings. The function can operate on tuples of arbitrary types:
composite :: [(a,a)] -> [(a,a)] -> [(a,a)]
As #Daniel Wagner observes in the comments, it's actually a little more complicated:
composite :: (Eq a) => [(a,a)] -> [(a,a)] -> [(a,a)]
The Eq a tells Haskell that a is something that you can compare for equality. Formally, a is a member of the Eq type class.
He also observes that we can generalize this further: the lefthand side of the tuples in list A don't have to be of the same type as the righthand side of the tuples in list B. So you could have, for example, a list of (Int,String) and a list of (String,Char), and match them on the String. The type would become:
composite :: Eq b => [(a, b)] -> [(b, c)] -> [(a, c)]
A final thing to note is that there may be duplicates in your resulting list. This is the case in your third test case.
The exercise probably doesn't require you to remove the duplicates.. yet.
Haskells libraries provide tools to remove duplicates. In a production setting, you should use these tools. But when learning, writing your own code to remove duplicates may be a useful exercise.
I've also got it in ideone.org. Don't worry about the "main" and "print" over there for now; just experiment with the function and see if you understand it.
S.L. Barth is on the right track, but isn't quite there. What you need to do is to go through the cartesian product of both lists, compare the y parts and if they match, then you can emit a tuple on the output.
This can easily be done with a list comprehension, such as this one:
[(x, z) | (x, y1) <- a, (y2, z) <- b, y1 == y2]
You should be able to wrap this in a function.
Note that if you want the function to be polymorphic, the type of it needs an Eq y constraint so that you can actually compare the y parts:
composite :: Eq y => [(x, y)] -> [(y, z)] -> [(x, z)]
I've managed to get xUnit working on my little sample assembly. Now I want to see if I can grok FsCheck too. My problem is that I'm stumped when it comes to defining test properties for my functions.
Maybe I've just not got a good sample set of functions, but what would be good test properties for these functions, for example?
//transforms [1;2;3;4] into [(1,2);(3,4)]
pairs : 'a list -> ('a * 'a) list //'
//splits list into list of lists when predicate returns
// true for adjacent elements
splitOn : ('a -> 'a -> bool) -> 'a list -> 'a list list
//returns true if snd is bigger
sndBigger : ('a * 'a) -> bool (requires comparison)
There are already plenty of specific answers, so I'll try to give some general answers which might give you some ideas.
Inductive properties for recursive functions. For simple functions, this amounts probably to re-implementing the recursion. However, keep it simple: while the actual implementation more often than not evolves (e.g. it becomes tail-recursive, you add memoization,...) keep the property straightforward. The ==> property combinator usually comes in handy here. Your pairs function might make a good example.
Properties that hold over several functions in a module or type. This is usually the case when checking abstract data types. For example: adding an element to an array means that the array contains that element. This checks the consistency of Array.add and Array.contains.
Round trips: this is good for conversions (e.g. parsing, serialization) - generate an arbitrary representation, serialize it, deserialize it, check that it equals the original.
You may be able to do this with splitOn and concat.
General properties as sanity checks. Look for generally known properties that may hold - things like commutativity, associativity, idempotence (applying something twice does not change the result), reflexivity, etc. The idea here is more to exercise the function a bit - see if it does anything really weird.
As a general piece of advice, try not to make too big a deal out of it. For sndBigger, a good property would be:
let ``should return true if and only if snd is bigger`` (a:int) (b:int) =
sndBigger (a,b) = b > a
And that is probably exactly the implementation. Don't worry about it - sometimes a simple, old fashioned unit test is just what you need. No guilt necessary! :)
Maybe this link (by the Pex team) also gives some ideas.
I'll start with sndBigger - it is a very simple function, but you can write some properties that should hold about it. For example, what happens when you reverse the values in the tuple:
// Reversing values of the tuple negates the result
let swap (a, b) = (b, a)
let prop_sndBiggerSwap x =
sndBigger x = not (sndBigger (swap x))
// If two elements of the tuple are same, it should give 'false'
let prop_sndBiggerEq a =
sndBigger (a, a) = false
EDIT: This rule prop_sndBiggerSwap doesn't always hold (see comment by kvb). However the following should be correct:
// Reversing values of the tuple negates the result
let prop_sndBiggerSwap a b =
if a <> b then
let x = (a, b)
sndBigger x = not (sndBigger (swap x))
Regarding the pairs function, kvb already posted some good ideas. In addition, you could check that turning the transformed list back into a list of elements returns the original list (you'll need to handle the case when the input list is odd - depending on what the pairs function should do in this case):
let prop_pairsEq (x:_ list) =
if (x.Length%2 = 0) then
x |> pairs |> List.collect (fun (a, b) -> [a; b]) = x
else true
For splitOn, we can test similar thing - if you concatenate all the returned lists, it should give the original list (this doesn't verify the splitting behavior, but it is a good thing to start with - it at least guarantees that no elements will be lost).
let prop_splitOnEq f x =
x |> splitOn f |> List.concat = x
I'm not sure if FsCheck can handle this though (!) because the property takes a function as an argument (so it would need to generate "random functions"). If this doesn't work, you'll need to provide a couple of more specific properties with some handwritten function f. Next, implementing the check that f returns true for all adjacent pairs in the splitted lists (as kvb suggests) isn't actually that difficult:
let prop_splitOnAdjacentTrue f x =
x |> splitOn f
|> List.forall (fun l ->
l |> Seq.pairwise
|> Seq.forall (fun (a, b) -> f a b))
Probably the only last thing that you could check is that f returns false when you give it the last element from one list and the first element from the next list. The following isn't fully complete, but it shows the way to go:
let prop_splitOnOtherFalse f x =
x |> splitOn f
|> Seq.pairwise
|> Seq.forall (fun (a, b) -> lastElement a = firstElement b)
The last sample also shows that you should check whether the splitOn function can return an empty list as part of the returned list of results (because in that case, you couldn't find first/last element).
For some code (e.g. sndBigger), the implementation is so simple that any property will be at least as complex as the original code, so testing via FsCheck may not make sense. However, for the other two functions here are some things that you could check:
pairs
What's expected when the original length is not divisible by two? You could check for throwing an exception if that's the correct behavior.
List.map fst (pairs x) = evenEntries x and List.map snd (pairs x) = oddEntries x for simple functions evenEntries and oddEntries which you can write.
splitOn
If I understand your description of how the function is supposed to work, then you could check conditions like "For every list in the result of splitOn f l, no two consecutive entries satisfy f" and "Taking lists (l1,l2) from splitOn f l pairwise, f (last l1) (first l2) holds". Unfortunately, the logic here will probably be comparable in complexity to the implementation itself.