Mutating elements of a list in Prolog - list

I am supposed to write a rule in SWI Prolog, which takes a list of characters as input and then replaces each letter by a random other character with a probability of 0.01.
Example:
?- mutate([a,b,c,d,e,f,g],MutatedList).
MutatedList = [a,b,c,a,e,f,g].
Can anyone tell me how that could be implemented? I am totally clueless so far about how this could work out in Prolog.
Thanks to anyone who can help!^^

This is relatively easy. You can use maplist/3 to relate the elements of the lists in a pairwise way. (Take a look at some of my notes on maplist/3].
For each pair [InputItem,OutputItem] sampled from [InputList,OutputList], maplist/3 will call a predicate, call it choose(InputItem,OutputItem).
That predicate will relate InputItem to the same value, InputItem or to a randomly chosen character (atom of length 1), which can be generated by selecting it randomly from a list of characters. The choice on whether to perform mutation can be made using random_float/0 for example.
Of course, choose(InputItem,OutputItem) is not really a predicate (it is just called that way, both in name at runtime), as it does not behave "predicatly" at all, i.e. it will have different outcomes depending on the time of day. It's an Oracle getting information from a magic reservoir. But that's okay.
Now you are all set. Not more than 4 lines!

Related

How to make predicate repeat N number of times in Prolog?

I have a number of lists containing letters and I have written a predicate that checks whether or not there are duplicates present in one of these given lists:
noDuplicates([]).
noDuplicates([H|T]):-
not(member(H, T)),
noDuplicates(T).
I have 10 lists and I want to know if there are no duplicates in any of them, so I made them into sublists of one big list, something like:
[[A,B,C], [C,A,D], [E,F,G]...]]
(So there can be duplicates in the big list, but not the individual sublists).
I get that I have to do the duplicates test 10 times; once for every sublist, but how do I write this in Prolog? I could probably write it down 10 times, but my guess is I can use recursion to make prolog repeat itself until all sublists have been checked.
So basically: I want this predicate to repeat itself N times, until N is 10. I'm really struggling with it though. Does anyone have any idea on what to do?
Let us generalize the question as follows:
You have a predicate p/1 that expresses what you want for a single list.
Thus, to lift this definition to a list of such lists, you can define a predicates ps/1 as follows:
ps([]).
ps([L|Ls]) :-
p(L),
ps(Ls).
Every time you see this pattern, you can use maplist/2. That is, the above is equivalent to:
ps(Ls) :- maplist(p, Ls).
The goal maplist(p, Ls) is true iff p holds for each element L of Ls.
Note that it will limit your understanding of Prolog if you think in terms of "looping" and "repeating". These are imperative notions and only make sense when the list is already fully instantiated. However, from Prolog, we expect more than that: We expect a full-fledged relation to also generate lists for which the relation holds. And in such cases, there is nothing to "repeat" yet: We start from nothing, and ask Prolog what solutions there are in general.
Thus, think in terms of describing when the relation ps/1 holds for lists of lists:
It holds for the empty list [].
It holds for the list [L|Ls] if our initial predicate (p/1) holds for L, and ps/1 holds for the remaining list Ls.
This declarative reading is applicable in all directions, no matter how many list elements are already instantiated, if any. It works for 10 lists just as well as for zero and 50.

Prolog - how to generate list of specific length?

I'm doing this exercise for which I have to write a predicate randomnames/1 for generating a random list of three names (no duplicates allowed). I have a database with 10 names in it already and they all correspond to a number, for example: name(1, Mary).
I wrote a predicate for generating one random name:
randomname(Name) :-
random(0, 11, N), % generate random integer between 1 and 10.
name(N, Name).
My question would be: How do I get this in a list? And a list of exactly three elements at that?
I don't want to use too many built-ins. length/2 would be alright though. I think I might need it :)
Thanks a lot!
Edit: I figured I would first try to generate a list of three random numbers (the names can come later). I wrote this horribly wrong little thing:
numberlist([N|T]) :-
random(0, 11, N),
length([N|T], 3),
numberlist(T).
I know how to do this with a /2 predicate; when the user can just enter in the query that they want a list with three elements (numberlist(3,X).for example). But I'm can't seem to figure out how to write down in code that I always want a list of three numbers.
I was also thinking of using findall for generating my list, but again I don't know how to limit the length of the list to three random elements.
When describing lists in Prolog, it is often useful to first describe how a single element looks like.
For example, in your case, it seems you already have a predicate like random_name/1, and it describes a single element of the list you want to describe.
So, to describe a list consisting of three such elements, what about:
random_names([A,B,C]) :-
random_name(A),
random_name(B),
random_name(C).
This describes a list with three elements, and random_name/1 holds for each of these elements.

Understanding the representation of inifinite lists as the limit of partial lists in haskell

I was going through this article which explains Haskell's non-strict semantics. I understood till the author starts talking about Partial and Infinite Lists in Haskell.
The author says :-
The idea is that an infinite list is to be understood as a limit of partial lists.
And after that, the author goes on to explain the execution of the expression :-
filter (< 3) [1..]
The result kinda goes against my intuition of my expected output. I thought the answer would be simply the list :- [1, 2]. But, nope!!. While the authors explain is sufficient to understand the execution process and how we get the final result, it doesn't explain why it works like so.
So, my question is why are infinite lists represented as the limit of a bunch of partial lists? Can someone explain this without digging too deep into complex mathematical jargon?
Thanks
To put things simply, the Haskell compiler is not magic, however magical it may sometimes appear. While certain sorts of expressions may seem extremely declarative compared to other programming languages, Haskell’s evaluation semantics are actually remarkably simple.
For this reason, in the example you mention, filter (< 3) [1..], GHC does not “know” anything about the meaning of the above expression. While it is obvious to a human than there will never be any elements after 2 that satisfy the (< 3) predicate, there is no reason that filter can be aware that there won’t eventually be some element that does. For this reason, attempting to evaluate anything other than the first two elements of the resulting list will produce an infinite loop.
This is the idea behind the explanation that infinite lists in Haskell are really just “limits”. A true analytical system can work with infinite lists, and it can make assertions about all of their elements. One can trivially prove, mathematically, that the infinite list represented by the Haskell expression [1..] only contains two elements that are less than 3, but Haskell does not have any such analytical capabilities—it’s just a functional programming language.
Using the analog to a mathematical limit, we can say that evaluating [1..] approaches the infinite list given an infinite amount of time and space, but without that, it’s just a computation—a promise that we can always produce more elements if we want, but unlike a mathematical infinite set, it is not some high level description of a truly infinite set of elements. It’s just a finite set of elements with an arbitrary size and a description of how to obtain more.

Prolog - Modifying and returning list

I want to define predicate which takes a list, adds an element to the list, let's say the number "1", and then returns the list.
I've found out I can add elements to a list using append/3, but I want to use in inside another predicate, thus why I want it to return "my modified list".
My object-oriented mindset tells me to ask the interpreter something like: ?-append(X,5,X). , so that it takes the list X, adds 5 to it, and returns "the new X", but I know that's not how unification works, so my mind is kinda in a glitch.
Can anyone please try to explain how something like this could be achievable?
You are already very close to the solution, so I only rephrase what you are beginning to sense already:
First, you cannot modify a list in pure Prolog.
Instead, you should think in terms of relations between entities. In your case, think in terms of relations between lists.
So, "adding the number 1" to a list is a relation between two lists, which could look like this:
list_with_one(Ls, [1|Ls]).
Note that this works in all directions! You can use it to:
generate answers
test particular cases
"reverse" the direction etc.
So, all you need to do in your case is to think in terms of relations between lists: One without an element, and how this relates to a different list with the element.
Obviously, these two lists will be indicated by different variables and different arguments.
Note in particular that append(X, 5, X) cannot hold: First of all, append/3 is meant to be a relation between lists, and 5 is not a list. Second, assuming you wrote for example append(Xs, [5], Xs), then this would be true if there where a list Xs such that if the element 5 were appended to Xs, the resulting list would again be Xs. Good luck finding such a list... Note also the naming convention to denote lists by letting the variable name end with an s.
It is also falls a bit short to blame this on your "object-oriented mindset", since you can have object oriented programming in Prolog too.
Although lists in Prolog cannot be modified, it is possible to add elements to the end of a list with an unspecified length. In this way, items can be "appended" to a list without creating another list:
:- initialization(main).
append_to_list(List,Item) :-
append_to_list(List,Item,0).
append_to_list(List,Item,Index) :-
% using SWI-Prolog's nth0 predicate
(nth0(Index,List,Check_Item),
var(Check_Item),
nth0(Index,List,Item));
(Next_Index is Index+1,
append_to_list(List,Item,Next_Index)).
main :-
A = [1,2,3|_],
append_to_list(A,4),
append_to_list(A,7),
writeln(A).
In this example, A becomes [1,2,3,4,7|_].

Are infinite lists useful for any real world applications?

I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?
Here's an utterly trivial but actually day-to-day useful example of where infinite lists specifically come in handy: When you have a list of items that you want to use to initialize some key-value-style data structure, starting with consecutive keys. So, say you have a list of strings and you want to put them into an IntMap counting from 0. Without lazy infinite lists, you'd do something like walk down the input list, keeping a running "next index" counter and building up the IntMap as you go.
With infinite lazy lists, the list itself takes the role of the running counter; just use zip [0..] with your list of items to assign the indices, then IntMap.fromList to construct the final result.
Sure, it's essentially the same thing in both cases. But having lazy infinite lists lets you express the concept much more directly without having to worry about details like the length of the input list or keeping track of an extra counter.
An obvious example is chaining your data processing from input to whatever you want to do with it. E.g., reading a stream of characters into a lazy list, which is processed by a lexer, also producing a lazy list of tokens which are parsed into a lazy AST structure, then compiled and executed. It's like using Unix pipes.
I found it's often easier and cleaner to just define all of a sequence in one place, even if it's infinite, and have the code that uses it just grab what it wants.
take 10 mySequence
takeWhile (<100) mySequence
instead of having numerous similar but not quite the same functions that generate a subset
first10ofMySequence
elementsUnder100ofMySequence
The benefits are greater when different subsections of the same sequence are used in different areas.
Infinite data structures (including lists) give a huge boost to modularity and hence reusability, as explained & illustrated in John Hughes's classic paper Why Functional Programming Matters.
For instance, you can decompose complex code chunks into producer/filter/consumer pieces, each of which is potentially useful elsewhere.
So wherever you see real-world value in code reuse, you'll have an answer to your question.
Basically, lazy lists allow you to delay computation until you need it. This can prove useful when you don't know in advance when to stop, and what to precompute.
A standard example is u_n a sequence of numerical computations converging to some limit. You can ask for the first term such that |u_n - u_{n-1}| < epsilon, the right number of terms is computed for you.
Now, you have two such sequences u_n and v_n, and you want to know the sum of the limits to epsilon accuracy. The algorithm is:
compute u_n until epsilon/2 accuracy
compute v_n until epsilon/2 accuracy
return u_n + v_n
All is done lazily, only the necessary u_n and v_n are computed. You may want less simple examples, eg. computing f(u_n) where you know (ie. know how to compute) f's modulus of continuity.
Sound synthesis - see this paper by Jerzy Karczmarczuk:
http://users.info.unicaen.fr/~karczma/arpap/cleasyn.pdf
Jerzy Karczmarcuk has a number of other papers using infinite lists to model mathematical objects like power series and derivatives.
I've translated the basic sound synthesis code to Haskell - enough for a sine wave unit generator and WAV file IO. The performance was just about adequate to run with GHCi on a 1.5GHz Athalon - as I just wanted to test the concept I never got round to optimizing it.
Infinite/lazy structures permit the idiom of "tying the knot": http://www.haskell.org/haskellwiki/Tying_the_Knot
The canonically simple example of this is the Fibonacci sequence, defined directly as a recurrence relation. (Yes, yes, hold the efficiency complaints/algorithms discussion -- the point is the idiom.): fibs = 1:1:zipwith (+) fibs (tail fibs)
Here's another story. I had some code that only worked with finite streams -- it did some things to create them out to a point, then did a whole bunch of nonsense that involved acting on various bits of the stream dependent on the entire stream prior to that point, merging it with information from another stream, etc. It was pretty nice, but I realized it had a whole bunch of cruft necessary for dealing with boundary conditions, and basically what to do when one stream ran out of stuff. I then realized that conceptually, there was no reason it couldn't work on infinite streams. So I switched to a data type without a nil -- i.e. a genuine stream as opposed to a list, and all the cruft went away. Even though I know I'll never need the data past a certain point, being able to rely on it being there allowed me to safely remove lots of silly logic, and let the mathematical/algorithmic part of my code stand out more clearly.
One of my pragmatic favorites is cycle. cycle [False, True] generates the infinite list [False, True, False, True, False ...]. In particular, xs ! 0 = False, xs ! 1 = True, so this is just says whether or not the index of the element is odd or not. Where does this show up? Lot's of places, but here's one that any web developer ought to be familiar with: making tables that alternate shading from row to row.
The general pattern seen here is that if we want to do some operation on a finite list, rather than having to construct a specific finite list that will “do the thing we want,” we can use an infinite list that will work for all sizes of lists. camcann’s answer is in this vein.