i need to write a code that should access to list that created. but i don't know how, i read this question: How do I store and access a list within a variable in Prolog?
but it wasn't my problem I create the list with this code:
p([Head|Tail]):-
read(Head),
p([Tail|Taile]).
my_write([Head|Tail]):- write(Head),nl,my_write(Tail).
and i need created list. what should i do ? it's make me confuse.
try
p(L) :-
( read(Head),
Head \= end_of_file
-> p(Tail),
L = [Head|Tail]
; L = []
).
Prolog is designed more for symbolic processing, IO, being based on side effects, it's often error prone.
Please note that read/1 it's actually a very powerful 'parser', being able to process generalized Prolog terms (structures, expressions, list, with arbitrary nesting).
At EOF, SWI-Prolog return the atom 'end_of_file', hence the test you see n the code.
Related
i am a beginner in ocaml and I am stuck in my project.
I would like to count the number of elements of a list contained in a list.
Then test if the list contains odd or even lists.
let listoflists = [[1;2] ; [3;4;5;6] ; [7;8;9]]
output
l1 = even
l2 = even
l3 = odd
The problem is that :
List.tl listoflists
Gives the length of the rest of the list
so 2
-> how can I calculate the length of the lists one by one ?
-> Or how could I get the lists and put them one by one in a variable ?
for the odd/even function, I have already done it !
Tell me if I'm not clear
and thank you for your help .
Unfortunately it's not really possible to help you very much because your question is unclear. Since this is obviously a homework problem I'll just make a few comments.
Since you talk about putting values in variables you seem to have some programming experience. But you should know that OCaml code tends to work with immutable variables and values, which means you have to look at things differently. You can have variables, but they will usually be represented as function parameters (which indeed take different values at different times).
If you have no experience at all with OCaml it is probably worth working through a tutorial. The OCaml.org website recommends the first 6 chapters of the OCaml manual here. In the long run this will probably get you up to speed faster than asking questions here.
You ask how to do a calculation on each list in a list of lists. But you don't say what the answer is supposed to look like. If you want separate answers, one for each sublist, the function to use is List.map. If instead you want one cumulative answer calculated from all the sublists, you want a fold function (like List.fold_left).
You say that List.tl calculates the length of a list, or at least that's what you seem to be saying. But of course that's not the case, List.tl returns all but the first element of a list. The length of a list is calculated by List.length.
If you give a clearer definition of your problem and particularly the desired output you will get better help here.
Use List.iter f xs to apply function f to each element of the list xs.
Use List.length to compute the length of each list.
Even numbers are integrally divisible by two, so if you divide an even number by two the remainder will be zero. Use the mod operator to get the remainder of the division. Alternatively, you can rely on the fact that in the binary representation the odd numbers always end with 1 so you can use land (logical and) to test the least significant bit.
If you need to refer to the position of the list element, use List.iteri f xs. The List.iteri function will apply f to two arguments, the first will be the position of the element (starting from 0) and the second will be the element itself.
My question is probably digging a bit into the question on how smart the F# compiler really is.
I have a type module that scans a configuration file and should then provide a range of IP addresses between a start and an end address.
type IpRange (config: string) =
// Parse the config
member __.StartIp = new MyIp(startIp)
member __.EndIp = new MyIp(endIp)
Now I wanted to add the actual range giving me all IPs so I added
member __.Range =
let result = new List<MyIp>()
let mutable ipRunner = __.StartIp
while ipRunner <= __.EndIp do
result.Add(new MyIp(ipRunner))
ipRunner <- (ipRunner + 1)
result
which works but is not really idiomatic F#.
I then dug into the issue and came up with the following two alternatives
let rec GetIpRangeRec (startIp: MyIp) (endIp: MyIp) (ipList: MyIp list) =
if startIp <= endIp then
GetIpRangeRec (startIp + 1) endIp (ipList#[startIp])
else
ipList
and
let GetIpRangeUnfold (startIp: MyIp) (endIp: MyIp) =
startIp |> Seq.unfold(fun currentIp ->
if (currentIp <= endIp) then
Some(currentIp, currentIp + 1)
else
None)
As far as I have understood from reading up on lists and sequences, none is cached. So all three solutions would re-evalute the code to create a list whenever I try to access an item or enumerate the list.
I could solve this problem by using Seq.cache (and a previous cast to sequence where required) resulting in something like
member __.Range =
GetIpRangeRec startIp endIp []
|> List.toSeq
|> Seq.cache
but is this really necessary?
I have the feeling that I missed something and the F# compiler actually does cache the result without explicitely telling it to.
Lists are (normally at least, I suppose there might be some weird edge case I don't know about) stored directly as their values. Thus, your recursive function would specifically produce a list of MyIps - these would only be re-evaluated if you have done some weird thing where a MyIp is re-evaluated each time it is accessed. As in, when the function returns you'll have a fully evaluated list of MyIps.
There is one slight issue, however, in that your function as implemented isn't particularly efficient. Instead, I would recommend doing it in this slightly alternative way:
let rec GetIpRangeRec (startIp: MyIp) (endIp: MyIp) (ipList: MyIp list) =
if startIp <= endIp then
GetIpRangeRec (startIp + 1) endIp (startIp :: ipList)
else
List.rev ipList
Basically, the issue is that every time you use the # operator to append to the end of a list, the runtime has to walk to the end of the list to do the append. This means that you'll end up iterating over the list a whole bunch of times. Instead, better simply to prepend (i.e. append, but to the front), and then reverse the list just before you return it. This means that you only have to walk the list once, as prepending is always a constant-time operation (you just create a new list entry with a pointer to the previous front of the list).
Actually, since you probably don't want to use a pre-supplied list outside of your function, I would recommend doing it this way instead:
let GetIpRange startIp endIp =
let rec GetIpRangeRec (start: MyIp) (end: MyIp) (ipList: MyIp list) =
if start <= end then
GetIpRangeRec (start + 1) end (start :: ipList)
else
List.rev ipList
GetIpRangeRec startIp endIp List.empty
(note that I haven't tested this, so it may not work totally perfectly). If you do want to be able to pre-supply a starting list, then you can just stick with the first one.
Also, bear in mind that while lists are usually fine for sequential access, they're terrible for random accesses. If you need to be doing random lookups into the list, then I would recommend using a call to List.toArray once you get the complete list back. Probably no need to bother if you'll just be iterating over it sequentially though.
I'll make one more point though: From a total functional programming 'purist's' perspective your first implementation may not be totally 'functional', but the only mutability involved is all hidden away inside the function. That is, you're not mutating anything that is passed in to the function. This is perfectly fine from a functional purity perspective and might be good for performance. Remember that F# is functional-first, not zealously fuctional-only ;)
EDIT: Just thought of one more thing I would like to add: I don't know exactly how your MyIp types are constructed, but if you can build them out of numbers, it might be worth looking at using a sequence comprehension like seq {1 .. 100} and then piping that to a map to create the MyIps, e.g. seq {1 .. 100} |> Seq.map makeIp |> Seq.toList. This would be the easiest way, but would only work if you can simply specify a simple number range.
Seq is lazy in F#, ie there are benefits to caching the results occassionally. F# List is not lazy, it's an immutable single linked list that won't get any benefits from caching.
I have browsed through various answers on SO about how to declare a list but I keep getting error messages. I am reading the section on lists from a book that I have but there still isn't an example on how to correctly declare them.
I am doing a project for my class. I have a random set of questions but when the user answers one then that question cannot be repeated (questions are to be random).
I have this part done but I wanted to create a list so that when a question is asked, I want to add that question number to my list. I have tried various ways and I still can't do it!
test(N):- list(P), member(N, P).
list = [].
start :-
write('Answer the questions correctly'), nl,
X is 0,
push(X,list,[X|list]),
test(X).
This snippet is just to make the list code. As I understand it I want to push X, in this case 0, to the head of the list. Since my list was declared as empty I figure it would work. I am getting this error:
No permission to modify static procedure `(=)/2'
I have tried to understand what this means but because everyone's code is different there are many different answers and I am overwhelmed. This is my first time programming in Prolog.
No permission to modify static procedure `(=)/2'
In Prolog you do not construct list by declaring them as you tried to do with
list = [].
Prolog values start with lower case letters and variables start with upper case letters. That is not common among programming languages but makes it easy to create new variables, you don't have to declare them, just use an upper case letter where you need a variable.
Prolog does not use assignment or have methods. Prolog uses syntactic unification and has predicates. So when you see [] as a argument being passed, that is when the list is either constructed, or unified with a variable.
You probably want something like this
begin :-
% In the next statement I am doing what you would consider
% constructing a list.
ask([]).
ask(List) :-
write('Answer the questions correctly'), nl,
get_answer(A),
% Here the answer in A is added to the head of the list using
% the list operator that combines a head with a tail, `|`.
% This is how your idea of a push is done with a list.
test([A|List]).
% When this is called from
% get_answer(A), A will be unified with 0.
get_answer(0).
% The next predicate `test` with two clauses does what your were trying to do with
% `member(N,P)`. It uses recursion which needs one clause to recursively process
% a list and one clause, the base case, to handle an empty list.
% When the list is empty, do nothing.
test([]).
test([H|T]) :-
% H is the head of the list
% do something with head of list by adding more code here.
% T is the tail of the list.
% Recursively call test with the tail of the list
% to process the remainder of the list.
test(T).
How can I build a predicate in prolog that receives a number and a list, I must insert the number in the list by the tail
I tried inserting the number in the list by the head: insert(H,[P|Q],[H,P|Q]). and it works, but how can I do it by the tail?
Simply use append/3 like this:
?- append([a,b,c,d],[x],List).
List = [a,b,c,d,x].
Inserting at the tail can be done with a two-part recursive rule:
When the list is empty, unify the result to a single-element list with the item being inserted
When the list is not empty, unify the result to a head followed by the result of inserting into the tail of a tail.
English description is much longer than its Prolog equivalent:
ins_tail([], N, [N]).
ins_tail([H|T], N, [H|R]) :- ins_tail(T, N, R).
Demo.
Nobody talked about difference lists yet.
Difference lists
Difference lists are denoted L-E, which is just a convenient notation for a couple made of a list L whose last cons-cell has E for its tail:
L = [ V1, ..., Vn | E]
The empty difference list is E-E, with E a variable. You unify E whenever you want to refine the list.
For example, if you want to add an element X, you can unify as follows:
E = [X|F]
And then, L-F is the new list. Likewise, you can append lists in constant time. If you unify F with a "normal" list, in particular [], you close your open-ended list. During all operations, you retain a reference to the whole list through L. Of course, you can still add elements in front of L with the ususal [W1, ..., Wm |L]-E notation.
Whether or not you need difference lists is another question. They are intereseting if adding an element at the end is effectively a common operation for you and if you are manipulating large lists.
Definite clause grammars
DCG are a convenient way of writing grammar rules in Prolog. They are typically implemented as reader macros, translating --> forms into actual predicates. Since the purpose of grammars is to build structures during parsing (a.k.a. productions), the translation to actual predicates involves difference lists. So, even though both concepts are theoretically unrelated, difference lists are generally the building material for DCGs.
The example on wikipedia starts with:
sentence --> noun_phrase, verb_phrase.
... which gets translated as:
sentence(S1,S3) :- noun_phrase(S1,S2), verb_phrase(S2,S3).
A lot of "plumbing" is provided by the syntax (a little like monads). The object being "built" by sentence/2 is S1, which is built from different parts joined together by the predicates. S1 is passed down to noun_phrase, which builds/extends it as necessary and "returns" S2, which can be seen as "whatever extends S1". This value is passed to verb_phrase which updates it and gives S3, a.k.a. whatever extends S2. S3 is an argument of sentence, because it is also "whatever extends S1", given the rule we have. But, this is Prolog, so S1, S2 and S3 are not necessarly inputs or outputs, they are unified during the whole process, during which backtracking takes place too (you can parse ambiguous grammars). They are eventually unified with lists.
Difference lists come to play when we encounter lists on the right-hand side of the arrow:
det --> [the].
The above rule is translated as:
det([the|X], X).
That means that det/2 unifies its first argument with an open-ended list which tail is X; other rules will unify X. Generally, you find epsilon rules which are associated with [].
All the above is done with macros, and a typical error is to try to call an auxiliary predicate on your data, which fails because the transformation add two arguments (a call to helper(X) is in fact a call to helper(X,V,W)). You must enclose actual bodies between braces { ... } to avoid treating prediates as rules.
Here is an another option.
insert(N,[],[N]).
insert(N,[H|T],[H|Q]) :- conc([H|T],[N],[H|Q]).
conc([],L,L).
conc([H|T],L,[H|Q]) :- conc(T,L,Q).
I'm a newbie to Haskell, I have a problem. I need to write a function that splits a list into a list of lists everywhere a 'separation' appears.
I will try to help you develop the understanding of how to develop functions that work on lists via recursion. It is helpful to learn how to do it first in a 'low-level' way so you can understand better what's happening in the 'high-level' ways that are more common in real code.
First, you must think about the nature of the type of data that you want to work with. The list is in some sense the canonical example of a recursively-defined type in Haskell: a list is either the empty list [] or it is some list element a combined with a list via a : list. Those are the only two possibilities. We call the empty list the base case because it is the one that does not refer to itself in its definition. If there were no base case, recursion would never "bottom out" and would continue indefinitely!
The fact that there are two cases in the definition of a list means that you must consider two cases in the definition of a function that works with lists. The canonical way to consider multiple cases in Haskell is pattern matching. Haskell syntax provides a number of ways to do pattern matching, but I'll just use the basic case expression for now:
case xs of
[] -> ...
x:xs' -> ...
Those are the two cases one must consider for a list. The first matches the literal empty list constructor; the second matches the element-adding constructor : and also binds two variables, x and xs', to the first element in the list and the sublist containing the rest of the elements.
If your function was passed a list that matches the first case, then you know that either the initial list was empty or that you have completed the recursion on the list all the way past its last element. Either way, there is no more list to process; you are either finished (if your calls were tail-recursive) or you need to pass the basic element of your answer construction back to the function that called this one (by returning it). In the case that your answer will be a list, the basic element will usually be the empty list again [].
If your function was passed a list that matches the second case, then you know that it was passed a non-empty list, and furthermore you have a couple of new variables bound to useful values. Based on these variables, you need to decide two things:
How do I do one step of my algorithm on that one element, assuming I have the correct answer from performing it on the rest of the list?
How do I combine the results of that one step with the results of performing it on the rest of the list?
Once you've figured the answers to those questions, you need to construct an expression that combines them; getting the answer for the rest of the list is just a matter of invoking the recursive call on the rest of the list, and then you need to perform the step for the first element and the combining.
Here's a simple example that finds the length of a list
listLength :: [a] -> Int
listLength as =
case as of
[] -> 0 -- The empty list has a length of 0
a:as' -> 1 + listlength as' -- If not empty, the length is one more than the
-- length of the rest of the list
Here's another example that removes matching elements from a list
listFilter :: Int -> [Int] -> Int
listFilter x ns =
case ns of
[] -> [] -- base element to build the answer on
n:ns' -> if n == x
then listFilter x ns' -- don't include n in the result list
else n : (listFilter x ns') -- include n in the result list
Now, the question you asked is a little bit more difficult, as it involves a secondary 'list matching' recursion to identify the separator within the basic recursion on the list. It is sometimes helpful to add extra parameters to your recursive function in order to hold extra information about where you are at in the problem. It's also possible to pattern match on two parameters at the same time by putting them in a tuple:
case (xs, ys) of
([] , [] ) -> ...
(x:xs', [] ) -> ...
([] , y:ys') -> ...
(x:xs', y:ys') -> ...
Hopefully these hints will help you to make some progress on your problem!
Let's see if the problem can be reduced in a obvious way.
Suppose splitList is called with xs to split and ys as the separator. If xs is empty, the problem is the smallest, so what's the answer to that problem? It is important to have the right answer here, because the inductive solution depends on this decision. But we can make this decision later.
Ok, so for problem to be reducable, the list xs is not empty. So, it has at least a head element h and the smaller problem t, the tail of the list: you can match xs#(h:t). How to obtain the solution to the smaller problem? Well, splitList can solve that problem by the definition of the function. So now the trick is to figure out how to build the solution for bigger problem (h:t), when we know the solution to the smaller problem zs=splitList t ys. Here we know that zs is the list of lists, [[a]], and because t may have been the smallest problem, zs may well be the solution to the smallest problem. So, whatever you do with zs, it must be valid even for the solution to the smallest problem.
splitList [] ys = ... -- some constant is the solution to the smallest problem
splitList xs#(h:t) ys = let zs = splitList t ys
in ... -- build a solution to (h:t) from solution to t
I don't know how to test it. Anybody tells me how to write a function to a .hs file and use winGHCi to run this function?
WinGHCi automatically associates with .hs files so just double-click on the file and ghci should start up. After making some changes to the file using your favourite editor you can write use the :r command in ghci to reload the file.
To test the program after fixing typos, type-errors, and ensuring correct indentation, try calling functions you have defined with different inputs (or use QuickCheck). Note Maybe is defined as Just x or Nothing. You can use fromMaybe to extract x (and provide default value for the Nothing case).
Also try to make sure that pattern matching is exhaustive.