Discussion:
Newbie list question
(trop ancien pour répondre)
Joel
2009-05-12 22:18:28 UTC
Permalink
Hello,

I'm trying to put together a simple list function that takes a string
and a list name as input, and then iterates through the list members to
see if that string exists. If the string doesn't exist, I want the
function to add the string to the head of the list.

Here's what I have, but it's not working the way I had hoped:

# let rec findordefine varname varlist = function
| [] -> varname::varlist
| [a] -> if a != varname then varname::varlist else varlist
| h::t ->
if h != varname then varname::varlist else varlist
;;
val findordefine : 'a -> 'a list -> 'a list -> 'a list = <fun>

# let a = [];;
val a : 'a list = []

# let hello="test";;
val hello : string = "test"

# findordefine hello a;;
- : string list -> string list = <fun>

# a;;
- : 'a list = []

I was hoping it would return the updated list. Can someone help me
understand what I'm doing wrong?

Thanks!
Joel
Joel
2009-05-12 22:48:13 UTC
Permalink
Cancel...
Post by Joel
Hello,
I'm trying to put together a simple list function that takes a string
and a list name as input, and then iterates through the list members to
see if that string exists. If the string doesn't exist, I want the
function to add the string to the head of the list.
# let rec findordefine varname varlist = function
| [] -> varname::varlist
| [a] -> if a != varname then varname::varlist else varlist
| h::t ->
if h != varname then varname::varlist else varlist
;;
val findordefine : 'a -> 'a list -> 'a list -> 'a list = <fun>
# let a = [];;
val a : 'a list = []
# let hello="test";;
val hello : string = "test"
# findordefine hello a;;
- : string list -> string list = <fun>
# a;;
- : 'a list = []
I was hoping it would return the updated list. Can someone help me
understand what I'm doing wrong?
Thanks!
Joel
Loading...